问题描述:

I wrote a clean function for my Django form. I defined OPTIONAL_PASSWORD_INPUT and OPTIONAL_REPEAT_PASSWORD_INPUT above as password input fields:

class addNewMemberForm(SignUpForm):

username = forms.SlugField(required=False,

min_length=MIN_USER_NAME,

max_length=MAX_USER_NAME,

label="Username (optional)",

help_text="If left empty, we will generate a username for you."

)

password = OPTIONAL_PASSWORD_INPUT

password2 = OPTIONAL_REPEAT_PASSWORD_INPUT

def clean(self):

# 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.")

return self.cleaned_data

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 self.data?

网友答案:

The individual field validation and cleaning is done prior to calling the form.clean. 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.

相关阅读:
Top