Stumbled this def clean_password2 ModelForm. My question is does every time this we run this view. Does it will automatically run clean_password2 to check the password or do we need to explicitly call it?
Form.py
class RegisterForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = User
fields = ('full_name', 'email',) #'full_name',)
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super(RegisterForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
user.is_active = False # send confirmation email via signals
# obj = EmailActivation.objects.create(user=user)
# obj.send_activation_email()
if commit:
user.save()
return user
https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#a-full-example
CodePudding user response:
No, you don't have to call it explicitly as it says in the doc.
The clean_<fieldname>() method is called on a form subclass – where <fieldname> 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).
doc: https://docs.djangoproject.com/en/4.0/ref/forms/validation/