Menu
CoddyTech

Pages by Slug

Part of the Class-Based Views section of Coddy's Django journey. Lesson 6 of 18.

/jobs/7/ says nothing about the job. /jobs/python-developer-brightline/ says what it is, to people and to search engines. That readable part is a slug: lowercase words joined by hyphens. Every Job already has one in its slug field.

When the URL argument is named slug, a DetailView finds the row whose slug field matches. Both names can change. A recipe site whose route is "recipes/<slug:recipe_slug>/" tells the view:

class RecipeDetailView(DetailView):
    model = Recipe
    slug_url_kwarg = "recipe_slug"

slug_url_kwarg names the URL argument and slug_field the model field; both default to "slug". Rename the URL argument without telling the view, and it finds neither a pk nor a slug and crashes.

challenge icon

Challenge

Easy

Move the job pages from ids to slugs:

  • In jobs/urls.py, the detail route takes the job's slug instead of its pk.
  • In job_list.html, each link passes the job's slug.

Press Run and click Python Developer on /jobs/: the address is /jobs/python-developer-brightline/.

Try it yourself

from django.urls import path

from . import views

app_name = "jobs"

urlpatterns = [
    path("", views.HomeView.as_view(), name="home"),
    path("about/", views.AboutView.as_view(), name="about"),
    path("jobs/", views.JobListView.as_view(), name="list"),
    path("jobs/<int:pk>/", views.JobDetailView.as_view(), name="detail"),
]

All lessons in Class-Based Views

Practice on your own: Django playground