Andrew Wilkinson

Random Ramblings on Programming

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>
About these ads

Written by Andrew Wilkinson

February 3, 2009 at 1:25 pm

Posted in web development

Tagged with , ,

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

Follow

Get every new post delivered to your Inbox.

Join 103 other followers

%d bloggers like this: