Login

Load initial form fields from GET parameters

Author:
ramen
Posted:
November 18, 2009
Language:
Python
Version:
1.1
Tags:
forms
Score:
-1 (after 5 ratings)

It is often convenient to be able to specify form field defaults via GET parameters, such as /contact-us/?reason=Sales (where "reason" is the name of a form field for which we want a default value of "Sales"). This snippet shows how to set a form's initial field values from matching GET parameters while safely ignoring unexpected parameters.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
def my_view(request):
    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
            # ...
            return HttpResponseRedirect('/thanks/')
    else:
        form = MyForm()

        # Load initial form fields from GET parameters
        for key in request.GET:
            try:
                form.fields[key].initial = request.GET[key]
            except KeyError:
                # Ignore unexpected parameters
                pass

    return render_to_response('my_template.html', {'form': form})

More like this

  1. Javascript Chain Select Widget by ogo 7 years, 1 month ago
  2. Prevent form tampering of hidden fields by theju 5 years, 6 months ago
  3. Add GET parameters from current request by naktinis 4 years, 2 months ago
  4. SeparatedValuesField by jezdez 7 years, 7 months ago
  5. Validator for data by limodou 8 years, 4 months ago

Comments

girasquid (on November 18, 2009):

Last time I did this, all I had to do was:

form = MyForm(initial=request.GET)

#

ramen (on November 18, 2009):

Oh, good point. That's quite a bit easier. I can still see some merit to this technique if you want different error handling or you want to exclude certain GET parameters. Thanks for the insight. I wish this technique was explained in the docs.

#

buriy (on November 18, 2009):

I'd use

form = MyForm(initial=request.POST or request.GET or None)

Here I used "None" to hide errors when no fields has been filled.

#

ramen (on May 28, 2010):

I'm back to using the method I described originally. Using MyForm(request.GET) is triggering form validation, and MyForm(initial=request.GET) is resulting in lists getting printed in the inputs ("[u'somevalue']") when using ModelForms. Thanks for the downvotes anyway.

#

nullpass (on May 13, 2014):

I know it's old but this thread still shows in Google for this problem. Here's the solution I'm using under Django 1.6

form = MyForm(initial=request.POST.dict())

I found .dict when during a dir() on request.POST.

#

Please login first before commenting.