Andrew Wilkinson

Random Ramblings on Programming

Dynamic Initial Values in Django Forms

with 3 comments

I recently had cause to create a form with two date time fields which had the default values of midnight seven days ago, and midnight this morning. Initially I thought this would be easy and created the following form.

from datetime import datetime, date, timedelta

class MyForm(forms.Form):
    date_from = forms.DateTimeField(label="From",
                               initial=(date.today() - timedelta(days=7)))
    date_to = forms.DateTimeField(label="To", initial=date.today())

This works fine except that when a process has been running across more than one day the initial values are no longer correct as they refer to the day the process started. Fortunately it appears that there is an undocumented feature where the initial value can be a function rather than an absolute value. This function is called each time the unbound form is displayed, so they are always correct.

Wrapping the code to create the value in a lambda works great here, as does passing a reference to a function.

from datetime import datetime, date, timedelta

class MyForm(forms.Form):
    date_from = forms.DateTimeField(label="From",
                 initial=lambda: (date.today() - timedelta(days=7)))
    date_to = forms.DateTimeField(label="To", initial=date.today)
Advertisements

Written by Andrew Wilkinson

January 28, 2009 at 1:33 pm

Posted in web development

Tagged with ,

3 Responses

Subscribe to comments with RSS.

  1. Why not just:

    f = MyForm(initial={‘date_from’: (date.today() – timedelta(days=7))}

    Tomasz

    July 22, 2009 at 12:35 am

  2. That would work, but to me it seems cleaner to have the defaults specified in the form rather than where you use it. What if you use the form in more than one place?

    Andrew Wilkinson

    August 6, 2009 at 11:57 am

  3. wolla initial it is easy on ear thanks 😀

    overcomes

    November 23, 2009 at 2:09 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: