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

lists/urls.py.

url

(

r'^(\d+)/$'

,

'lists.views.view_list'

,

name

=

'view_list'

),

url

(

r'^new$'

,

'lists.views.new_list'

,

name

=

'new_list'

),

The {% url %} Template Tag

We can replace the hardcoded URL in

home.html

with a Django template tag which

refers to the URL’s “name”:

lists/templates/home.html (ch10l026-1).

{% block form_action %}{% url 'new_list' %}{% endblock %}

We check that doesn’t break the unit tests:

$

python3 manage.py test lists

OK

Let’s do the other template. This one is more interesting, because we pass it a parameter:

lists/templates/list.html (ch10l026-2).

{% block form_action %}{% url 'view_list' list.id %}{% endblock %}

Check out the

Django docs on reverse URL resolution

for more info.

We run the tests again, and check they all pass:

$

python3 manage.py test lists

OK

$

python3 manage.py test functional_tests

OK

Excellent:

$

git commit -am"Refactor hard-coded URLs out of templates"

Remove hardcoded URLs from views.py

Remove hardcoded URL from forms in

list.html and home.html

Remove duplication of validation logic in

views

Using get_absolute_url for Redirects

Now let’s tackle

views.py

. One way of doing it is just like in the template, passing in the

name of the URL and a positional argument:

188

|

Chapter 10: Input Validation and Test Organisation