Sunday, 6 September 2015

Day 13 - forms

A Simple Form-Handling Example

Continuing this book’s ongoing example of books, authors and publishers, let’s create a simple view that lets users search our book database by title.
Generally, there are two parts to developing a form: the HTML user interface and the backend view code that processes the submitted data. The first part is easy; let’s just set up a view that displays a search form:
from django.shortcuts import render

def search_form(request):
    return render(request, 'search_form.html')
As we learned in Chapter 3, this view can live anywhere on your Python path. For sake of argument, put it inbooks/views.py.
render (request, name of template html in '')
The accompanying template, search_form.html, could look like this:
<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>
The URLpattern in urls.py could look like this:
from mysite.books import views

urlpatterns = patterns('',
    # ...
    url(r'^search-form/$', views.search_form),
    # ...
)
(Note that we’re importing the views module directly, instead of something likefrom mysite.views import search_form, because the former is less verbose. We’ll cover this importing approach in more detail in Chapter 8.)
Now, if you run the runserver and visit http://127.0.0.1:8000/search-form/, you’ll see the search interface. Simple enough.
Try submitting the form, though, and you’ll get a Django 404 error. The form points to the URL /search/, which hasn’t yet been implemented. Let’s fix that with a second view function:
# 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)
For the moment, this merely displays the user’s search term, so we can make sure the data is being submitted to Django properly, and so you can get a feel for how the search term flows through the system. In short:
  1. 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/.
  2. The Django view that handles the URL /search/ (search()) has access to the q value in request.GET.

No comments:

Post a Comment