Menu
CoddyTech

Named URLs

Part of the Django Basics section of Coddy's Django journey. Lesson 10 of 23.

The home page should link to About. Typing "/about/" into every link works until the address changes, and then every link breaks. Instead, give each route a name and build the address from it. A shop app's urls.py:

app_name = "shop"

urlpatterns = [
    path("cart/", views.cart, name="cart"),
    path("products/<slug:slug>/", views.product, name="product"),
]
app_name puts the names in a namespace: the full name is "shop:cart", so two apps can each have a home. reverse() turns a name back into an address. With the shop included under shop/:
reverse("shop:cart")                    # "/shop/cart/"
reverse("shop:product", args=["mug"])   # "/shop/products/mug/"

Change "cart/" to "basket/" and every address built from the name follows.

challenge icon

Challenge

Easy
  • In menu/urls.py, set app_name = "menu" and name every route: home, about, hours, contact, table, drink, order.
  • On the home page, after the paragraph, add a link <a href="...">About us</a> whose address comes from reverse("menu:about").

Press Run and click About us.

Try it yourself

from django.urls import path

from . import views

urlpatterns = [
    path("", views.home),
    path("about/", views.about),
    path("hours/", views.hours),
    path("contact/", views.contact),
    path("table/<int:number>/", views.table),
    path("drinks/<slug:slug>/", views.drink),
    path("order/", views.order),
]
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Django Basics

Practice on your own: Django playground