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
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Last time I did this, all I had to do was:
#
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.
#
I'd use
Here I used "None" to hide errors when no fields has been filled.
#
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.
#
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.
#
I use this snippet
#
Please login first before commenting.