What You'll Learn in This Hour |
|
In Hour 10, "Adding Forms to Views," you learned how to create Form objects and render them as HTML. In this hour, we will extend that concept and show you how to use rendered forms to update the database.
The following sections take you through the process of displaying the Form during a GET request, retrieving the updated data from the form in a POST request, validating the data, and updating the database.
The first step in using Django Forms to update the database is to handle the GET and POST requests properly. Because the GET request is the initial request to just view the page, the request has no form data. When the user clicks the submit button on the form, Django receives a POST request that contains the form data and that can be processed.
The type of request can be determined by accessing the HttpRequest object that is sent to the view function. For a GET request, the value of the request is 'GET'. For a POST request, the value is 'POST'.
For example, the following code snippet checks to see if the HttpRequest is a GET or POST request:
def my_view(request): if request.method == 'GET': #handle GET if request.method == 'POST': #handle POST
Try It Yourself: Handle GET and POST Requests in a ViewIn this section, you will add an update button to the person_from.html template and update the person_form() view to detect whether the request is a GET or POST. Follow these steps to add GET and POST request handling to the person_form() view:
By the Way Notice that the form's data is blank after the POST request is submitted. This is because in the POST handler, we did not get the instance of the Person object and apply it to the form. Listing 11.1. Full Contents of iFriends/templates/People/person_form.html
Listing 11.2. Full Contents of the person_form() view in iFriends/People/views.py
|