简体   繁体   中英

Django forms - cleaned_data KeyError

I have a form that looks like the following:

class AForm(forms.ModelForm):
    email1 = forms.EmailField(required=False, initial='')
    email2 = forms.EmailField(required=False)

    class Meta:
        model = AModel
        fields = ()

    def clean_email1(self):
        return self.cleaned_data['email1'].lower()

    def clean_email2(self):
        return self.cleaned_data['email2'].lower()

    def clean(self):
        cleaned_data = super(AForm, self).clean()
        email1 = cleaned_data['email1']   # ERR
        email2 = cleaned_data['email2']
        # ...

It is used in a view post method in the following way:

form = AForm(request.POST, instance=self.object)
if forms.is_valid():
    # ...
else:
    # ...

It happens sometimes that my users produce a KeyError in clean at the line marked with ERR .

I don't understand how this is possible since, as the documentation reads , cleaned_data should contain (as dict keys) all the fields of the form.

Also I can't reproduce the error when I test sending nothing for email1 and email2 (or blank/empty values).

What am I missing here?

You've explicitly marked email1 as required=False. That means it's perfectly possible to get to clean with no value for that field, in which case it will not be included in the cleaned_data dict.

To guard against that, you can use the normal dict get method:

email1 = cleaned_data.get('email1')

or, of course, you could make the field required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM