I wrote a clean function for my Django form. I defined
OPTIONAL_REPEAT_PASSWORD_INPUT above as password input fields:
username = forms.SlugField(required=False,
help_text="If left empty, we will generate a username for you."
password = OPTIONAL_PASSWORD_INPUT
password2 = OPTIONAL_REPEAT_PASSWORD_INPUT
# if user name is filled out, so must be the password field.
if self.data["username"] and not self.data["password"]:
raise forms.ValidationError("If you specify a username, you must specify a password.")
def __init__(self, *args, **kwargs):
super(SignUpForm, self).__init__(*args, **kwargs)
self.fields.keyOrder = uniqueify(['username', 'email'] + self.fields.keyOrder)
If I change
if self.data["username"] and not self.data["password"]: to
if self.cleaned_data["username"] and not self.cleaned_data["password"]:, Django produces a key error for "username."
Why is it that I can access values of the
self.data array, but not those of the
self.cleaned_data array in my clean function?
On another note, does this question even matter? Could I just use
The individual field validation and cleaning is done prior to calling the
username is added to the cleaned_data only if the entered data was valid. This means you should either use
self.cleaned_data.get or check if there are any errors on
self.errors early in your clean and just bail on the additional validation which might not be necessary if the individual fields are not valid.