Django form not calling clean_

后端 未结 2 1908
我寻月下人不归
我寻月下人不归 2021-02-06 02:59

I am attempting to validate a form (and it used to work before). For some reason, I can\'t seem to get the various cleaning functions such as clean_username(self) to get called

相关标签:
2条回答
  • 2021-02-06 03:09

    I discovered the source of the error after diving into the Django forms.py source.

    It seems that if a field is left blank, the form raises a ValidationError for that field after calling field.clean(), but it then does not call clean_<fieldname>, but it still calls the main clean method of the class. In order to deal with a clean method that uses those blank fields you have to do the following:

    def clean(self):
        try:
            password = self.cleaned_data['password']
            # etc
        except KeyError:
            raise ValidationError('The password field was blank.')
    
        return self.cleaned_data
    
    0 讨论(0)
  • 2021-02-06 03:22

    You can override this by using required=False in your field constructors.

    username = forms.CharField(max_length=30, required=False)
    password = forms.CharField(max_length=30,widget=forms.PasswordInput, required=False)
    

    This seems illogical for your example, but can be useful if other instances

    0 讨论(0)
提交回复
热议问题