Django Forms
Getting Data From the Request Object
HttpRequest objects contain several pieces of information about the currently requested URL. You should always use these attributes/methods instead of hard-coding URLs in your views.
Example
# BAD! def current_url_view_bad(request): return HttpResponse("Welcome to the page at /current/")
# GOOD def current_url_view_good(request): return HttpResponse("Welcome to the page at %s" % request.path)
Other Information About the Request
- request.META is a Python dictionary containing all available HTTP headers for the given request
- Because request.META is just a basic Python dictionary, you’ll get a KeyError exception if you try to access a key that doesn’t exist. You should either use a try/except clause or the get() method to handle the case of undefined keys.
# BAD! def ua_display_bad(request): ua = request.META['HTTP_USER_AGENT'] # Might raise KeyError! return HttpResponse("Your browser is %s" % ua)
# GOOD (VERSION 1) def ua_display_good1(request): try: ua = request.META['HTTP_USER_AGENT'] except KeyError: ua = 'unknown' return HttpResponse("Your browser is %s" % ua)
# GOOD (VERSION 2) def ua_display_good2(request): ua = request.META.get('HTTP_USER_AGENT', 'unknown') return HttpResponse("Your browser is %s" % ua)
Information About Submitted Data
- Beyond basic metadata about the request, HttpRequest objects have two attributes that contain information submitted by the user: request.GET and request.POST.
A Simple Form-Handling Example
Example: The search_form() in views.py
from django.shortcuts import render_to_response def search_form(request): return render_to_response('search_form.html')
Example: The accompanying template, search_form.html
<html> <head> <title>Search</title> </head> <body> <form action="/search/" method="get"> <input type="text" name="q"> <input type="submit" value="Search"> </form> </body> </html>
Example: The URLpattern in urls.py
from mysite.books import views urlpatterns = patterns('', # ... (r'^search-form/$', views.search_form), # ... )
The form points to the URL /search/.
# urls.py urlpatterns = patterns('', # ... (r'^search-form/$', views.search_form), (r'^search/$', views.search), # ... )
# views.py def search(request): if 'q' in request.GET: message = 'You searched for: %r' % request.GET['q'] else: message = 'You submitted an empty form.' return HttpResponse(message)
- The HTML <form> defines a variable q. When it’s submitted, the value of q is sent via GET (method="get") to the URL /search/.
- The Django view that handles the URL /search/ (search()) has access to the q value in request.GET
Example: To hook the user’s search query into the book database.
from django.http import HttpResponse from django.shortcuts import render_to_response from mysite.books.models import Book def search(request): if 'q' in request.GET and request.GET['q']: q = request.GET['q'] books = Book.objects.filter(title__icontains=q) return render_to_response('search_results.html', {'books': books, 'query': q}) else: return HttpResponse('Please submit a search term.')
Form Class
- Django comes with a form library, called django.forms, that handles many of the form issues.
- The primary way to use the forms framework is to define a Form class for each HTML <form> you’re dealing with.
insert the code here
page_revision: 2, last_edited: 1256721734|%e %b %Y, %H:%M %Z (%O ago)





