On 16/11/11 14:32, Jaroslav Dobrek wrote:
Hello,

I have got a class Person:

class Person(models.Model):
     given_names = models.CharField(max_length=200)
     family_names = models.CharField(max_length=200)
     date_of_birth = models.DateField(blank=True)

and a class PersonForm:

class PersonForm(forms.ModelForm):

     def clean_date_of_birth(self):
         try:
             date_of_birth = self.cleaned_data['date_of_birth']
             if date_of_birth.year<  1890:
                 raise forms.ValidationError(u"It is very improbable
for a person to be this old.")
             return date_of_birth
         except KeyError:
             pass

The code works as expected if I leave out "blank=True" in the field
date_of_birth of the class Person. But it doesn't work with
blank=True.

How does clean_date_of_birth have to look like, if date_of_birth is
optional?

Jaroslav


Hi Jaroslav,

When blank=True, you need to check that the user has entered a date_of_birth before you try to access its year.

    def clean_date_of_birth(self):
        date_of_birth = self.cleaned_data.get('date_of_birth')
        if date_of_birth:
            if date_of_birth.year < 1890:
                raise forms.ValidationError(u"It is very improbable...")
        return date_of_birth

Regards,
Alasdair

--
Alasdair Nicol
Developer, MEMSET

mail: alasd...@memset.com
 web: http://www.memset.com/

Memset Ltd., registration number 4504980. 25 Frederick Sanger Road, Guildford, 
Surrey, GU2 7YD, UK.

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to