我目前遇到了一个我无法解决的问题。
我自己写了一个简单的表格来更新用户的密码。在构造函数中,我想在输入字段中添加一个特定的类,如果有错误的话。基本上这是在POST请求之后和我验证表单后发生的。
班级:
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
你可以看到我写了这句话:
logger.debug(self.fields[f].error_messages)
在我的控制台中显示了我:
[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>}
这很有趣,因为我只请求页面但没有提交表格!从哪里来的?显然它没有填写。因为我的网站上没有显示错误消息。
我的模板如下所示:
<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>
答案 0 :(得分:2)
您应该使用is_valid()
方法而不是__init__()
方法添加代码,因为在初始化期间不会进行验证。
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