Andrew Wilkinson

Random Ramblings on Programming

Posts Tagged ‘forms

Using Django Forms For GET Urls

leave a comment »

A regular occurance in writing webapps is the user will submit a form, and on the results page you’ll want to include a link which the user can click to resubmit the form. This lets users bookmark the page or you can add an extra parameter such as ‘format’ so they can download the results.

While Django forms contain several functions for converting the form to HTML, it doesn’t contain one to convert a bound form to url arguments.

Fortunately Python’s standard library module urllib contains a module which converts a dictionary to a properly formatted url argument string. We simply add a function, as_url_args, which passes the form’s cleaned data to this function and we get back a nice string we can add to a link.

import urllib
from django import forms

class MyForm(forms.Form):
    name = forms.CharField

    def as_url_args(self):
        return urllib.urlencode(self.cleaned_data)    

To use this in a template, where form is the form object, we can add it to a link.

<a href="/form?{{ form.as_url_args }}&format=csv">Download As CSV</a>

Written by Andrew Wilkinson

February 3, 2009 at 1:25 pm

Posted in web development

Tagged with , ,

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)

Written by Andrew Wilkinson

January 28, 2009 at 1:33 pm

Posted in web development

Tagged with ,