As I am getting more into Django stuff I also seem to step into rookie mistakes. Hereby some (beginner) notes.
For validating of a particular field in Django a form class method can be defined, e.g.
from django import forms class MyForm(forms.Form): first_field = forms.CharField() second_field = forms.CharField() def clean_first_field(self): first_field = self.cleaned_data['first_field']
Well, so far so good. But there is a catch which cost me another sleepless hour last night. When the method for field1 is called the ‘self.cleaned_data’ dictionary does not contain the ‘field2’ yet!!
Try the following:
def clean_field1(self): first_field = self.cleaned_data['first_field'] second_field = self.cleaned_data['second_field'] # This will result in a KeyError exception!
Apparently Django will call the clean_xxx() methods in the same sequence as they are defined and will only supply the values UP TO AND INCLUDING the field being ‘cleaned’, but NOT the fields defined AFTER it. Watta…
This means if you want to check e.g. field1 and field2 between each other (yes, there are other ways of doing that as well, but when you’re only so far through the Django book you don’t know about them :)), then you have to check for the LAST field you want to check against to get values of this and PREVIOUSLY defined fields. So the code becomes:
def clean_first_field(self): first_field = self.cleaned_data['first_field'] # This is OK, field1 is defined before field2 second_field = self.cleaned_data['second_field'] # As this is called for field2 you can get its value as well.
Of course you should have more error-checking logic, the examples above are simplified for illustrative reasons.
Note that if you use the higher-level clean() method it will be called when all values are filled in.