Login

Load initial form fields from GET parameters

Author:
ramen
Posted:
November 18, 2009
Language:
Python
Version:
1.1
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 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.

#

tbazadaykin (on January 7, 2016):

I use this snippet

from forms import MyForm

def my_view(request, *args, **kwargs):
    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
            # ...
            return HttpResponseRedirect('/thanks/')
    else:
        if request.GET:
            test_form = MyForm(data=request.GET)
            test_form.is_valid()
            form = MyForm(initial=test_form.cleaned_data)
        else:
            form = MyForm()
        return render_to_response('my_template.html', {'form': form})

#

Please login first before commenting.