tkbe

November 8, 2006

Django :: making a date dropdown field

Filed under: django — tb @ 3:30 am

It seems like it is hard to input valid dates in a free-form text format for a significant portion of users. Personally, I don't like many of the popup calendar widgets since they usually rely on Javascript for rendering -- making your form useless to people that don't use Javascript in their browser. (To Javascript, or not to Javascript is a discussion for another time, but I'm quite sure Javascript shouldn't be used for pretty graphic effects.) Quite a number of the Javascript calendar widgets I've seen only allow you to skip backwards one month at a time, and that gets really tedious if you're as old as me and trying to find your birthday ;-)

An easy alternative is the traditional dropdown lists for months, days, and years. One way to implement that in Django is of course to have a separate SelectField for months, days, years and leave it to the template code to lay them out sensibly. I don't like that solution for several reasons: it's too much complexity at the wrong abstraction layer (I want to deal with a date-widget as one unit in my template code), formatting according to local customs becomes harder, and it will end up sprinkling conversion code all over your app if you're not careful. It turns out that it's not that hard to create a custom widget that does it all for you automatically...

Note: This code is minimalist in many ways. E.g. using localized month names, localized day/month/year ordering, using empty defaults, etc. is left as an excercise for the reader.

First lets define a convenience function for creating a dropdown list (we'll be responsible for the raw html in our widget, so it's probably not a good idea to use an existing Django Field -- I haven't tried that though, so I might be wrong):

PYTHON:
  1. def select(options, selected, name):
  2.     selected = str(selected)
  3.     options = [(str(v),str(v)) for v in options]
  4.     res = ['<select name="%s">' % name]
  5.     for k,v in options:
  6.         tmp = '<option '
  7.         if k == selected:
  8.             tmp += 'selected '
  9.         tmp += 'value="%s">%s</option>' % (k,v)
  10.         res.append(tmp)
  11.     res.append('</select>')
  12.     return '\n'.join(res)

Now for the DropDown (DD) DateField (it's about 35 LOC without all the explanatory comments):

PYTHON:
  1. class DDDateField(forms.FormField):
  2.     # you might want to add a year range to this...
  3.     def __init__(self, field_name='', is_required=False):
  4.         self.field_name = field_name
  5.         self.validator_list = [self.validator]
  6.         self.is_required = is_required
  7.  
  8.         # for convenience (we'll insert html select tags into the
  9.         # form to hold year/month/day data, and we'll name
  10.         # them as follows):
  11.         self.dayname = field_name + '_day'
  12.         self.monthname = field_name + '_month'
  13.         self.yearname = field_name + '_year'       
  14.  
  15.     # extract_data is called with a copy of the POST data.
  16.     # Remember that all the fields will be empty the first time
  17.     # around and that POST data is always text (and so should
  18.     # any default values that you set be).
  19.     # The return value from this method is later passed on to
  20.     # the render method (after the user has had an opportunity
  21.     # to mess with it).
  22.     # NOTE: if anything throws here, your widget won't show up.
  23.     def extract_data(self, post):
  24.         name = self.field_name
  25.         day = post.get(self.dayname, '1')
  26.         month = post.get(self.monthname, '1')
  27.         year = post.get(self.yearname, '1970')
  28.         value = post.get(name, '%s-%s-%s' % (year, month, day))
  29.         return dict(day=day, month=month, year=year, value=value)
  30.  
  31.     # now for the actual rendering. We're getting data from extract_data (above).
  32.     def render(self, data):
  33.         name = self.field_name
  34.         vals = (self.get_id(), name, forms.escape(data['value']))
  35.  
  36.         # put a hidden input tag here fun fun (we'll have to overwrite this value
  37.         # later..)
  38.         h = '<input type=hidden id="%s" name="%s" value="%s" />' % vals
  39.  
  40.         # using the convenience function from above
  41.         day = select(range(1,32), data['day'], self.dayname)
  42.  
  43.         # I haven't checked if it's possible to get localized month names from
  44.         # the calendar module, but if it is, they could go here:
  45.         month = select(range(1,13), data['month'], self.monthname)
  46.         year = select(range(1920, 2007), data['year'], self.yearname)
  47.         slash = '&nbsp;/&nbsp;'
  48.  
  49.         # use US ordering
  50.         widget = h + str(month) + slash + str(day) + slash + str(year)
  51.  
  52.         return widget
  53.  
  54.     # Unfortunately there is no way for the hidden field to get updated
  55.     # on a successful submission since render isn't called. The validator
  56.     # is called at this point though, and it has access to the entire set
  57.     # of form data. We're going to hijack it to tie up our lose ends
  58.     def validator(self, field_data, alldata):
  59.         # get the values from the subwidgets
  60.         y = alldata[self.yearname]
  61.         m = alldata[self.monthname]
  62.         d = alldata[self.dayname]
  63.  
  64.         # set the fieldname to the combined value
  65.         val = '%s-%s-%s' % (y,m,d)
  66.         alldata[self.field_name] = val
  67.  
  68.         # delete all the gunk we put in the form
  69.         del alldata[self.yearname], alldata[self.monthname], alldata[self.dayname]
  70.  
  71.         # there is no way for a user to enter an invalid date, so just
  72.         # return True.
  73.         return True
  74.    
  75.     # now all that's left for html2python is to extract data from above
  76.     # and return a Python object.
  77.     @staticmethod
  78.     def html2python(data):
  79.         # we're getting the data from the validator...
  80.         y, m, d = map(int, data.split('-'))
  81.         return datetime.date(y,m,d)

That's it, it can be used as any other field.

4 Comments »

  1. Thanks for the Django posts. Keep em coming.

    Comment by Josh — November 8, 2006 @ 6:04 pm

  2. Help, i’m want to make this work, but i got error ‘DDDateField’ object has no attribute ‘label’ :( try ed to add label no changes..

    Comment by martins — February 10, 2008 @ 2:37 am

  3. The DDDateField is using the “old-forms” framework, so my first guess is that you’re using newforms…? If that’s the case, there’s a similar widget in django.newforms.extras.widgets.SelectDateWidget. If you are using oldforms, I can take a closer look at it…

    Comment by tb — February 10, 2008 @ 1:21 pm

  4. thank you for turning me on to SelectDateWidget
    it rocks and u rock

    Comment by ryan — October 31, 2008 @ 10:21 pm

RSS feed for comments on this post. TrackBack URI

Leave a comment

Powered by WordPress