Sumit Jha
Sumit Jha

Reputation: 2195

Trouble understanding basic of Django Forms

This is the forms.py file:

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

    def clean(self):
        #super(MyForm, self).clean()
        if any(self.errors):
            print self.errors
            return
        value = self.cleaned_data['data']
        if int(value)%2 != 0:
            print "invalid data"
            raise forms.ValidationError(_("Please enter an even number"))

This is my view.py file:

def home(request):
    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
            return HttpResponse("thanks")
    else:
        form = MyForm()
    context = {
        'form': form,
    }

    return render(request, 'todayhome.html', context)

And this is my todayhome.html file:

<form method="post" action="">{% csrf_token %}
{{form.as_p}}
{{authorformset}}
<input type="submit" value="submit" name="submit"/>
</form>

What I don't understand is :

  1. Do I need to call

    super(MyForm, self).clean()
    

inside 'clean' method of forms.py explicitly, or will it be called automatically once I do

    self.errors?
  1. If I remove

    if any(self.errors):
        print self.errors
        return
    

    from the 'clean' method of forms.py file and submit the form empty, it renders shows

     'KeyError (data)'
    

instead of showing 'This field is required.' Why is it so ?

Upvotes: 0

Views: 49

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213401

Do I need to call super(MyForm, self).clean() inside 'clean' method of forms.py explicitly, or will it be called automatically once I do

You need to call it explicitly. That is the method which populates the self.errors attribute, when some error is found. Using self.errors you're just accessing that attribute, not calling any method.

For your second question, it shows KeyError while accessing self.cleaned_data['data'] (in case when you call super clean method), because when a particular key is added to self.errors, it is not added to self.cleaned_data. You need to check the key existence or self.errors first, before accessing any cleaned_data key.

Upvotes: 1

Related Questions