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:
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:
The URLpattern in urls.py could look like this:
(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:
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:
- 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.