django form max_length不起作用

时间:2016-01-14 02:42:59

标签: django django-forms

我正在使用django 1.8.7。我注意到表单的max_length不起作用。即使设置了max_length并且后续代码的密码长度大于50,表单也会生效。虽然min_length验证工作正常。

class AuthenticationForm(forms.Form):
    email_mobile = forms.CharField(widget=forms.TextInput, label="Email or Mobile")
    password = forms.CharField(widget=forms.PasswordInput, label="Password", min_length=6, max_length=50, error_messages={'min_length': 'Password should be at least 6 characters long.'})
    remember_me = forms.BooleanField(widget=forms.CheckboxInput, required = False)

    def clean(self):
        cleaned_data = super(AuthenticationForm, self).clean()
        try:
            if 'email_mobile' in self.cleaned_data:
                int(self.cleaned_data['email_mobile'])
                if len(self.cleaned_data['email_mobile']) != 10:
                    raise forms.ValidationError("Please provide a valid 10 digit mobile number.")
        except (ValueError, TypeError):
            if 'email_mobile' in self.cleaned_data:
                validate_email(self.cleaned_data['email_mobile'])

        return self.cleaned_data

我做错了什么还是错误?

2 个答案:

答案 0 :(得分:0)

我发现了自己的错误。我使用的表单输入已经在html中设置了50个maxlength字符,当我使用selenium发送密钥时,它不会超过50个字符。

答案 1 :(得分:0)

根据Docs,仅接受一个参数:render_value。另外,构造函数也没有其他任何参数:https://docs.djangoproject.com/en/2.2/_modules/django/forms/widgets/#PasswordInput

尝试以表格清理的方式进行清理。另外,如果要将其存储在模型的CharField中,则可以满足您的目的。