class AdminModelFormformsModelForm confirm_password = formsCharFieldlabel=确认密码 widget=formsPasswordInputrender_value=True class Meta model = modelsAdmin fields = username password
class AdminModelForm(forms.ModelForm): confirm_password = forms.CharField(label='确认密码', widget=forms.PasswordInput(render_value=True))
class Meta:
model = models.Admin
fields = ['username', 'password']
widgets = {
'password': forms.PasswordInput(render_value=True),
'username': forms.TextInput(attrs={'class': 'form-control'}),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field_name in self.fields:
field = self.fields[field_name]
field.widget.attrs.update({'class': 'form-control'})
def clean_confirm_password(self):
password = self.cleaned_data.get('password')
confirm_password = self.cleaned_data.get('confirm_password')
if confirm_password != password:
raise ValidationError('密码不一致,请重新输入')
return confirm_password
def admin_add(request): """添加管理员""" title = '新建管理员'
if request.method == 'GET':
form = AdminModelForm()
return render(request, 'change.html', {'form': form, 'title': title})
form = AdminModelForm(data=request.POST)
if form.is_valid():
form.save()
return redirect('admin_list')
else:
errors = form.errors.as_data()
return render(request, 'change.html', {'title': title, 'form': form, 'errors': errors}
原文地址: https://www.cveoy.top/t/topic/flBq 著作权归作者所有。请勿转载和采集!