SelectTimeWidget: A custom Django Widget

Published on 2008-11-18 19:40:00+00:00
Python   django  

I've been meaning to write this blog post for quite some time...

Django Models provide a way to create a definitive source of data for web applications. Written as a python class, a Django Model consists of Fields that (among other things) define a type for your data.

Django's Forms provide a mechanism for generating HTML form elements and validating user input. A sublcass of Django's Form class is the ModelForm which essentially creates a Form based on the Fields in a Model. Form Fields and Model Fields are not the same--though there is a mapping from Model fields to Form fields, however. The Fields in a Form define the validation logic for the data entered into the html form elements generated by the Field.

When Django renders a Form, it chooses an appropriate html form element (such as input, textarea, or select elements) based on the type of Fields in the Form. For example a form to save a URL with an associated title might look something like the following:

from django import forms  
class LinkForm(forms.Form):  
    title = forms.CharField()   
    url = forms.URLField()  

The HTML generated by calling this forms as_table() method might look something like this:

>>> f = LinkForm()  
>>> f.as_table()  
<tr><th>Title:</th><td><input type="text" name="title" /></td></tr>  
<tr><th>Url:</th><td><input type="text" name="url"/></td></tr>  

We can change the behaviour of this output HTML by specifying a specific widget for the Form. If for some strange reason we wanted the Title to render in a textarea, we would do the following:

title = forms.CharField(widget=forms.Textarea)  

All of this is well-documented in Django's Widget documentation, which has been working well for me 80% of the time.

My big complaint here is that Date and Time information defaults to text input elements. In the past, I've always liked to use select elements for situations when users would need to enter things like dates (perhaps a different select element for Months, Days, and Years) and time (different select elements for Hours, Minutes...

Luckily, (as of version 1.0, I think), Django offers a SelectDateWidget (located in django.forms.extras.widgets) which accomplishes this very thing. It produces three select elements, and it can be attached to a Form's DateField. This is accomplished like so:

some_date = forms.DateField(widget=SelectDateWidget,  

That's Awesome! I can even tell the widget to default to "today's" date by passing it an initial parameter containing the value generated by Ok... what about times? Would we ever want to enter Time information as three separate select elements. I do, so I basically altered the SelectDateWidget, creating a SelectTimeWidget, which is available on django snippets. It isn't perfect, but for now, it has accomplished what I've wanted... and its fairly flexible.

# Specify a basic 24-hr time Widget (the default)  
t = forms.TimeField(widget=SelectTimeWidget())  
# Force minutes and seconds to be displayed in increments of 10  
t = forms.TimeField(widget=SelectTimeWidget(minute_step=10, second_step=10))  
# Use a 12-hr time format, which will display a 4th select   
# element containing a.m. and p.m. options)  
t = forms.TimeField(widget=SelectTimeWidget(twelve_hr=True))  

However, I often use DateTimeFields in both Models and Forms (which consists of date and time info). All the code I need to represent select elements for such a field exists in both SelectDateWidget and SelectTimeWidgets. The problem? I just have figured out a good (read: proper) way to combine these two Widget classes.

Do I use multiple inheritance here... mixins... ? My experience doing this in python is a bit rusty... (erm, non-existent!) Hopefully the helpful django community will help me out. :)

UPDATE: This discussion is continued in Extending Django's MultiWidget: SplitSelectDateTimeWidget. I found a solution to this problem simply by digging through Django's source code. Huzzah for Open Source!

So if you had a project called mysite and an app called myapp, putting it all together would look something like this:

# in  
urlpatterns += patterns('',  
    (r'^test/$', 'mysite.myapp.views.test'),  
# in  
class TestForm(forms.Form):  
    t = forms.TimeField(widget=SelectTimeWidget(minute_step=15, second_step=30, twelve_hr=True))  
# in  
def test(request):  
    from forms import TestForm  
    if request.method == 'POST':  
        form = TestForm(request.POST)  
        if form.is_valid():  
            info = form.cleaned_data  
        form = TestForm()  
    return render_to_response('myapp/test.html',  

And the test.html Template:

{% extends "base.html" %}  
{% block content %}  
    {% if info %}  
        <pre>{{ info }}</pre>  
    {% else %}  
        <form action="" method="post">  
        {{\_p }}  
        <p><input type="submit" value="go"/></p>  
    {% endif %}  
{% endblock %}