sefakilic
sefakilic

Reputation: 1230

Django form.clean(), cleaned_data KeyError

In Django 1.4 documentation, it says that clean_<fieldname> methods are run first, then form clean method is executed.

I have the following code sample. The form is used with FormPreview. When pmid field is empty in the form, it should throw ValidationError exception, but it doesn't happen.

class MyForm(forms.Form):
    pmid = forms.CharField()
    .. other fields ..

    def clean(self):
        cd = super(MyForm, self).clean()
        cd['pmid'] # returns KeyError and it's not in cd
        return cd

I don't override any clean_<field> method.

Upvotes: 2

Views: 5027

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239260

First, if all you want to do is ensure a field is not blank, then just add required=True to it. For example:

class MyForm(forms.Form):
    pmid = forms.CharField(required=True)
    ...

And you're done.

However, even if you couldn't do it that way, you still wouldn't validate it in clean, but in clean_<fieldname> as the docs describe.

def clean_pmid(self):
    pmid = self.cleaned_data.get('pmid')
    if not pmid:
        raise forms.ValidationError('pmid cannot be blank')
    return pmid

Upvotes: 2

Related Questions