YouTip LogoYouTip

Django Blog Url Routing

In this chapter, you will learn Django's dynamic routing configuration to implement article detail pages and link navigation between pages. * * * ## What is Dynamic Routing? The homepage displays all articles, and each article needs its own independent detail page. URLs should look like this: `/post/1/`, `/post/2/`, where the numeric part is the article's primary key (pk). Dynamic routing allows variables in the URL, and Django will automatically extract and pass them to the view function. * * * ## Configure Dynamic Routing ## Example # File path: blog/urls.py from django.urls import path from . import views urlpatterns =[ path('', views.index, name='index'), # int:pk β€” Integer parameter in URL, named pk (primary key) # name='post_detail' β€” Name the route, use {% url %} in template to reference path('post//', views.post_detail, name='post_detail'), ] Route Converter Description: | Converter | Example Path | Matching Rule | | --- | --- | --- | | `` | /post/3/ | Matches positive integers | | `` | /post/django-guide/ | Matches strings (without /) | | `` | /post/django-guide/ | Matches letters, numbers, -, _ | | `` | /post/uuid/ | Matches UUID format | * * * ## Write Detail Page View The detail page needs to query the corresponding article from the database based on the pk in the URL. ## Example # File path: blog/views.py from django.shortcuts import render, get_object_or_404 from .models import Post def post_detail(request, pk): """Article detail page""" # get_object_or_404: Query single record # Returns object if found, automatically returns 404 page if not found (no need to write try/except) post = get_object_or_404(Post, pk=pk) context ={ 'post': post, 'title': f'{post.title} - TUTORIAL Blog' } return render(request,'blog/post_detail.html', context) > `get_object_or_404` is Django's best practice. It is equivalent to `Post.objects.get(pk=pk)` + `try/except Post.DoesNotExist`, but the code is more concise. When users visit a non-existent article ID, they will see a friendly 404 page instead of an error. * * * ## Create Detail Page Template ## Example {% extends 'blog/base.html' %} {% block title %}{{ post.title }} - TUTORIAL Blog{% endblock %} {% block content %}
{{ post.category.name }}

{{ post.title }}

{{ post.content|safe }}
← return to homepage
{% endblock %} ### Detail Page Style ## Example /* Add to base.html style */ .post-view{ max-width:720px; margin:0 auto; } .category-tag{ display: inline-block; padding:4px 12px; background:#e8f5e9; color:#2e7d32; border-radius:12px; font-size:13px; margin-bottom:12px; } .post-view h1 { font-size:32px; margin-bottom:12px; line-height:1.4; } .post-view time { display:block; color:#999; font-size:14px; margin-bottom:30px; } .content{ line-height:1.8; font-size:16px; color:#333; } .content h2 { margin:24px 0 12px; font-size:22px; } .content p { margin-bottom:12px; } .back-link{ display: inline-block; margin-top:40px; color:#2c3e50; text-decoration:none; } > The `|safe` filter tells Django: this content is safe HTML, render it directly, do not escape. Make sure content is trusted when using safe (such as content you edited in Admin). Never add safe to user-submitted content, otherwise there is XSS risk. * * * ## Generate Links in Template: {% url %} Add detail page link to article cards on the homepage. ## Example
{% for post in posts %}
{{ post.category.name }}

{{ post.title }}

{{ post.summary|truncatechars:80 }}

{{ post.created_at|date:"Y-m-d" }}
{% endfor %}
`{% url 'post_detail' post.pk %}` will automatically generate the correct URL based on the route name and parameters. If the route changes later (e.g., `/post/` changed to `/article/`), the links in the template will automatically update without manual modification. * * * ## Add get_absolute_url() to Model Define this method in the Post model to allow Admin backend, Django built-in tools, etc. to automatically find the detail page link. ## Example # Add to Post class in blog/models.py from django.urls import reverse class Post(models.Model): # ... field definitions ... def __str__ (self): return self.title def get_absolute_url(self): # reverse looks up URL based on route name and parameters return reverse('post_detail', kwargs={'pk': self.pk}) * * * ## Chapter Summary In this chapter, you mastered Django routing core concepts: dynamic routing `` to pass parameters, get_object_or_404 for safe queries, {% url %} template tag to generate links, and reverse to look up URLs. Now the blog has two pages: the homepage list and the article detail page. Click on cards to jump and read the full article.
← Django Blog AuthDjango Blog Admin β†’