Background Image
Table of Contents Table of Contents
Previous Page  211 / 478 Next Page
Information
Show Menu
Previous Page 211 / 478 Next Page
Page Background

Django Pattern: Processing POST Requests in the Same

View as Renders the Form

This time we’ll use a slightly different approach, one that’s actually a very common

pattern in Django, which is to use the same view to process POST requests as to render

the form that they come from. Whilst this doesn’t fit the REST-ful URL model quite as

well, it has the important advantage that the same URL can display a form, and display

any errors encountered in processing the user’s input.

The current situation is that we have one view and URL for displaying a list, and one

view and URL for processing additions to that list. We’re going to combine them into

one. So, in

list.html

, our form will have a different target:

lists/templates/list.html (ch10l020).

{% block form_action %}/lists/{{ list.id }}/{% endblock %}

Incidentally, that’s another hardcoded URL. Let’s add it to our to-do list, and while we’re

thinking about it, there’s one in

home.html

too:

Remove hardcoded URLs from views.py

Remove hardcoded URL from forms in

list.html and home.html

This will immediately break our original functional test, because the

view_list

page

doesn’t know how to process POST requests yet:

$

python3 manage.py test functional_tests

[...]

selenium.common.exceptions.NoSuchElementException: Message: 'Unable to locate

element: {"method":"css selector","selector":".has-error"}' ; Stacktrace:

[...]

AssertionError: '2: Use peacock feathers to make a fly' not found in ['1: Buy

peacock feathers']

In this section we’re performing a refactor at the application level. We

execute our application-level refactor by changing or adding unit

tests, and then adjusting our code. We use the functional tests to tell

us when our refactor is complete and things are back to working as

before. Have another look at the diagram from the end of

Chapter 4

if you need to get your bearings.

Django Pattern: Processing POST Requests in the Same View as Renders the Form

|

183