Named URLs

The rule. Give every route a name, and never write a path by hand anywhere else.

A hard-coded /post/3/ in a template works until the day you change the address, at which point it silently becomes a broken link. A named URL is looked up, so it changes with the route.

Three places you use the name.

In a template: {% url 'posts:detail' post.pk %}

In Python: reverse("posts:detail", args=[post.pk])

On the model: define get_absolute_url and then redirect(post) and {{ post.get_absolute_url }} both work.

The app_name prefix keeps names unique between apps, so posts:detail and accounts:detail can both exist.

◈ Graded Challenge

Write match_route(pattern, path) that does what Django's routing does, in miniature. The pattern is a string like "post/<int:pk>/" and the path is an address like "post/12/". Split both on slashes and compare piece by piece. A literal piece must match exactly. A piece written as <int:name> matches only digits and contributes {name: the number as an int}. A piece written as <str:name> matches any non-empty piece and contributes {name: the text}. Return a dictionary of the captured values when everything matches, and None when it does not.

Name it exactly: match_route(pattern, path)

Python4 visible + 4 hidden
loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back