Django Form Init检查字段是否存在将CSS类应用于该字段的错误
我现在遇到了一个我无法解决的问题 我给自己写了一个简单的表单来更新用户的密码。在构造函数中,如果有错误,我想在输入字段中添加一个特定的类。基本上,这是在POST请求之后以及我验证表单之后发生的 班级:Django Form Init检查字段是否存在将CSS类应用于该字段的错误,django,forms,Django,Forms,我现在遇到了一个我无法解决的问题 我给自己写了一个简单的表单来更新用户的密码。在构造函数中,如果有错误,我想在输入字段中添加一个特定的类。基本上,这是在POST请求之后以及我验证表单之后发生的 班级: class UpdatePasswordForm(forms.Form): """ This form is used at two places: - A user has been logged out and needs to reset the passwo
class UpdatePasswordForm(forms.Form):
"""
This form is used at two places:
- A user has been logged out and needs to reset the password
- A user is in the control panel and wants to update the password
"""
user = None
def_error_messages = {
'current_password_not_correct': _("Derzeitiges Passwort nicht ok."),
'password_mismatch': _("The two password fields didn't match."),
'password_tooshort': _("The password is too short."),
'password_tooeasy': _("The password is too easy or based on dictionary word."),
}
PASS_MIN_LENGTH = 8
current_password = forms.CharField(label=_("Derzeitiges Passwort"), widget=forms.PasswordInput)
password1 = forms.CharField(label=_("Password"),
widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"),
widget=forms.PasswordInput,
help_text=_("Enter the same password as above, for verification."))
def __init__(self, *args, **kwargs):
super(UpdatePasswordForm, self).__init__(*args, **kwargs)
for f in self.fields:
if self.fields[f].error_messages is not None:
logger.debug(self.fields[f].error_messages)
self.fields[f].widget.attrs['class'] = 'invalid'
def clean_current_password(self):
current_password = self.cleaned_data.get('current_password')
if current_password and self.user:
if check_password(current_password, self.user.password):
return True
raise forms.ValidationError(
self.def_error_messages['current_password_not_correct'],
code='current_password_not_correct',
)
return False
def has_digits(self, val):
digits = False
if any(c.isdigit() for c in val):
digits = True
return digits
def has_alpha(self, val):
ascii = False
if any(c in string.ascii_letters for c in val):
ascii = True
return ascii
def clean_password1(self):
password1 = self.cleaned_data.get("password1")
if len(password1) < self.PASS_MIN_LENGTH:
raise forms.ValidationError(
self.def_error_messages['password_tooshort'],
code='password_tooshort',
)
# check if it contains numbers
digits = self.has_digits(password1)
# check for normal char
ascii = self.has_alpha(password1)
if not digits and not ascii:
raise forms.ValidationError(
self.def_error_messages['password_tooeasy'],
code='password_tooeasy',
)
return password1
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.def_error_messages['password_mismatch'],
code='password_mismatch',
)
return password2
def save(self, commit=True):
customer = self.user
customer.set_password(self.cleaned_data["password1"])
customer.passwordreset = False
customer.resetdatetime = timezone.now()
customer.resetunifier = ""
if commit:
customer.save()
return customer
在我的控制台中显示:
[Fri Oct 23 04:08:30.837138 2015] [wsgi:error] [pid 49999] [23/Oct/2015 04:08:30] DEBUG [syslog:968] {u'required': <django.utils.functional.__proxy__ object at 0x7fd39242bbd0>}
[Fri Oct 23 04:08:30.837351 2015] [wsgi:error] [pid 49999] [23/Oct/2015 04:08:30] DEBUG [syslog:968] {u'required': <django.utils.functional.__proxy__ object at 0x7fd39242bbd0>}
[Fri Oct 23 04:08:30.837561 2015] [wsgi:error] [pid 49999] [23/Oct/2015 04:08:30] DEBUG [syslog:968] {u'required': <django.utils.functional.__proxy__ object at 0x7fd39242bbd0>}
[Fri-Oct 23 04:08:30.837138 2015][wsgi:error][pid 49999][23/Oct/2015 04:08:30]调试[syslog:968]{u'required':}
[Fri Oct 23 04:08:30.837351 2015][wsgi:error][pid 49999][23/Oct/2015 04:08:30]调试[syslog:968]{u'required':}
[Fri Oct 23 04:08:30.837561 2015][wsgi:error][pid 49999][23/Oct/2015 04:08:30]调试[syslog:968]{u'required':}
这很有趣,因为我只要求页面,但没有提交表格!所需资源来自哪里?很明显,它没有填写。因为我的网站上没有显示错误消息
我的模板如下所示:
<div class="input-field">
<label>{{ password_form.current_password.label }}</label>
{{ password_form.current_password }}
{% for error in password_form.current_password.errors %}
<span class="help-block">{{ error }}</span>
{% endfor %}
</div>
{{password\u form.current\u password.label}
{{password\u form.current\u password}}
{%用于密码形式中的错误。当前密码。错误%}
{{error}}
{%endfor%}
您应该将代码添加到is\u valid()
方法中,而不是\u init\u()
方法中,因为在初始化过程中不会进行验证
class UpdatePasswordForm(forms.Form):
...
def is_valid(self):
is_valid = super(UpdatePasswordForm, self).is_valid()
for f in self.fields:
if self.fields[f].error_messages is not None:
logger.debug(self.fields[f].error_messages)
self.fields[f].widget.attrs['class'] = 'invalid'
return is_valid
我认为在
\uuuu init\uuuu()
方法中添加该代码是无法做到这一点的,因为在初始化过程中不会进行任何验证。相反,我将尝试在is\u valid()
方法中添加代码。@RodXavier如果您将其作为答案,我将接受它。这就解决了问题!
class UpdatePasswordForm(forms.Form):
...
def is_valid(self):
is_valid = super(UpdatePasswordForm, self).is_valid()
for f in self.fields:
if self.fields[f].error_messages is not None:
logger.debug(self.fields[f].error_messages)
self.fields[f].widget.attrs['class'] = 'invalid'
return is_valid