I have a pretty simple form:
from django import forms
class InitialSignupForm(forms.Form):
email = forms.EmailField()
password = forms.CharField(max_length=255, widget = forms.PasswordInput)
password_repeat = forms.CharField(max_length=255, widget = forms.PasswordInput)
def clean_message(self):
email = self.clean_data.get('email', '')
password = self.clean_data.get('password', '')
password_repeat = self.clean_data.get('password_repeat', '')
try:
User.objects.get(email_address = email)
raise forms.ValidationError("Email taken.")
except User.DoesNotExist:
pass
if password != password_repeat:
raise forms.ValidationError("The passwords don't match.")
Is this how custom form validation is done? I need to evaluate on email
that no users currently exist with that email address. I also need to evaluate that password
and password_repeat
match. How can I go about doing this?
To validate a single field on it's own you can use a clean_FIELDNAME() method in your form, so for email:
then for co-dependant fields that rely on each other, you can overwrite the forms
clean()
method which is run after all the fields (likeemail
above) have been validated individually:I'm not sure where you got
clean_message()
from, but that looks like it is a validation method made for amessage
field which doesn't seem to exist in your form.Have a read through this for more details:
https://docs.djangoproject.com/en/dev/ref/forms/validation/