Ilya Voytov
Ilya Voytov

Reputation: 339

How to clean optional Django Form fields

I have a Django search form with an optional fields. If the field is used, it should be validated in clean_{field_name}. However I keep getting '>' not supported between instances of 'NoneType' and 'datetime.date' Error when the field is left empty. When I do a Request URL:http://localhost:8000/dockets/p_CentralGrocers/ (so no query parameters are passed at all), the cleaned_data parameter still has a blank item for the field name, which leads to a datetime comparison with a blank field which causes the error. What is the best way to handle optional fields in the cleaning process?

  1 from django import forms
  2 from django.core.exceptions import ValidationError 
  3 from django.utils.translation import ugettext_lazy as _
  4 import datetime
  5                                          
  6 class SearchDocketForm(forms.Form):      
  7                                          
  8     from_date = forms.DateField(help_text="Enter start date for search", required=False)
  9     to_date = forms.DateField(help_text="Enter to date for search", required=False) 
 10 
 11     def clean_from_date(self):           
 12         data = self.cleaned_data['from_date']
 13         if not data return ''                                                                      
 14 
 15         # check if date is in the past   
 16         if data > datetime.date.today(): 
 17             raise ValidationError(_('Invalid date - from date in the future'))
 18         return data

Upvotes: 1

Views: 443

Answers (1)

Adharsh M
Adharsh M

Reputation: 3832

First, I Believe

'>' not supported between instances of 'NoneType' and 'datetime.date'

is an issue with the parsing.

The Data will be simply String when you post it. eg: "01/01/2001" Will be the value of data if you're posting any values.

you must change it in to datetime object before comparison.

from datetime import datetime

.....
def clean_from_date(self):
    data = self.cleaned_data['from_date']
    if not data return ''                                                                      
    # Parse according to the format you're planning to post.
    data = datetime.strptime(data, "%D %M %Y")
    if data > datetime.date.today(): 
        raise ValidationError(_('Invalid date - from date in the future'))
    return data

Secondly, Verify if you have any

from_date = models.DateField(default=datetime.now())

set in models.py.

Tip: Try print(data) before the if statement, it will give you contents of data in console.

Upvotes: 2

Related Questions