Search code examples
djangodjango-formsdjango-validation

How clean_botcatcher(self): automatically called?


I got confused, does django automatically calls clean_botcatcher(self): . Does it acts as listener which got triggered when bot makes changes to values?

from django import forms
class FormName(forms.Form):
    name = forms.CharField()
    email = forms.EmailField()
    text = forms.CharField(widget=forms.Textarea)
    botcatcher = forms.CharField(required=False,widget =forms.HiddenInput)

    def clean_botcatcher(self):
            botcatcher = self.cleaned_data['botcatcher']
            if len(botcatcher) > 0:
                raise forms.ValidationError("Gotcha BOT")
            return botcatcher

Solution

  • The clean_() method is called on a form subclass – where is replaced with the name of the form field attribute. This method does any cleaning that is specific to that particular attribute, unrelated to the type of field that it is. This method is not passed any parameters. You will need to look up the value of the field in self.cleaned_data and remember that it will be a Python object at this point, not the original string submitted in the form (it will be in cleaned_data because the general field clean() method, above, has already cleaned the data once).

    For example, if you wanted to validate that the contents of a CharField called serialnumber was unique, clean_serialnumber() would be the right place to do this. You don’t need a specific field (it’s a CharField), but you want a formfield-specific piece of validation and, possibly, cleaning/normalizing the data.

    The return value of this method replaces the existing value in cleaned_data, so it must be the field’s value from cleaned_data (even if this method didn’t change it) or a new cleaned value.

    reference https://docs.djangoproject.com/en/4.0/ref/forms/validation/