Learn Django · 3/13

URLs and Views: Directing Traffic 🚦

6 min read

Welcome to the control center of your Django application.

If you’ve set up your project, you currently have a fancy Python script that does… absolutely nothing visible. To make a web application works, it needs to know how to handle visitors.

Imagine you are running a massive hotel (your Django Project).

  1. The Guest (The Request): A user types a URL into their browser.
  2. The Receptionist (The URL Dispatcher): Look at where the guest wants to go and directs them to the correct room.
  3. The Room Service (The View): Actually does the work—cleans the room, delivers food, or just tells the guest "Sorry, this room doesn't exist."

In this section, we are going to wire up the brain of your application.


1. URL Dispatcher: Mapping Routes to Views

Definition

The URL Dispatcher is a configuration system in Django that matches the requested URL pattern (the address in the browser) to a Python function that should handle it.

The Problem

Without a dispatcher, your server receives a request for yourwebsite.com/profile but has no idea which piece of code is responsible for displaying the profile. It’s like walking into a library where all the books are in a pile on the floor—you can't find what you need.

The Solution: urls.py

Django uses a file called urls.py to keep a list of "paths." When a request comes in, Django runs down this list top-to-bottom. The first one that matches wins.

Industry Standard: The include() method

In a professional environment, you never dump all your URLs into the main project urls.py. You split them by "apps" to keep things clean.

Step 1: Main Project urls.py
Located in myproject/urls.py

python
from django.contrib import admin
from django.urls import path, include # Import include

urlpatterns = [
    path('admin/', admin.site.urls),
    # Hand off any traffic starting with 'blog/' to the blog app
    path('blog/', include('blog.urls')), 
]

Step 2: App Level urls.py
Create this file in blog/urls.py (it doesn't exist by default)

python
from django.urls import path
from . import views # We will create this next

urlpatterns = [
    # Empty string means 'blog/' + '' = 'yourwebsite.com/blog/'
    path('', views.home), 
    path('about/', views.about),
]

🧠 Interesting Fact: Django’s URL resolver is compiled into a regular expression object in memory. This means even if you have hundreds of URL patterns, looking up a route is incredibly fast because it's mathematically optimized!


2. Function-Based Views (FBVs): Handling Requests & Responses

Definition

A View is a Python function that takes a Web request and returns a Web response. That response can be the HTML of a Web page, a redirect, a 404 error, an XML document, or an image.

The Problem

The URL dispatcher knows where to send the user, but it doesn't know what to do with them. We need logic to fetch data from the database and hand it to the user.

The Solution: The View Function

We write standard Python functions. The first argument must always be request (an object containing metadata about the user, browser, data sent, etc.).

Located in blog/views.py

python
from django.shortcuts import render
from django.http import HttpResponse

# 1. The simplest view possible (Good for testing)
def home(request):
    return HttpResponse("<h1>Welcome to the Blog! 🚀</h1>")

# 2. The Industry Standard (Rendering Templates)
def about(request):
    # Logic goes here (e.g., fetch database info)
    context = {
        'author': 'FreeCodeCamp Student',
        'mood': 'Happy'
    }
    # render(request, template_name, context_dictionary)
    return render(request, 'blog/about.html', context)

What happens under the hood?

  1. Django calls about(request).
  2. The render function loads the HTML file.
  3. It injects the context data into the HTML placeholders.
  4. It packages everything into an HttpResponse object and sends it back to the browser.

3. Dynamic URLs: Passing Parameters in Paths

Definition

Dynamic URLs allow you to capture values from the URL structure itself and pass them as arguments to your view function.

The Problem

Imagine you are building a social network. You have 1 million users.

  • /user/1
  • /user/2
  • /user/3

You cannot write 1 million paths in urls.py. You need a way to say: "If the URL looks like /user/ followed by any number, send that number to the view."

The Solution: Path Converters

We use angle brackets < > to capture data.

In blog/urls.py:

python
urlpatterns = [
    # Syntax: <converter:variable_name>
    path('post/<int:post_id>/', views.post_detail),
]

In blog/views.py:

python
from django.shortcuts import render, get_object_or_404
from .models import Post # Assuming you have a Post model

def post_detail(request, post_id):
    # post_id is passed automatically from the URL
    
    # INDUSTRY STANDARD: get_object_or_404
    # Don't manually try/except DoesNotExist. This shortcut handles it.
    post = get_object_or_404(Post, pk=post_id)
    
    return render(request, 'blog/detail.html', {'post': post})

Common Converters:

  • int: Matches zero or any positive integer (IDs).
  • str: Matches any non-empty string (excluding the path separator /).
  • slug: Matches letters, numbers, hyphens, and underscores (e.g., my-first-post).

🔥 Hot Tip: Always use slugs for public-facing URLs (like blog posts). yoursite.com/post/django-guide is much better for SEO (Search Engine Optimization) than yoursite.com/post/432.


4. Naming URLs & The Power of the reverse Function

Definition

URL Naming is the practice of assigning a unique keyword to a specific URL pattern. Reverse resolution is the process of generating a URL string by asking Django: "What is the URL for the pattern named 'blog-home'?"

The Problem

Scenario: You hardcoded <a href="/blog/archive/"> in 50 different HTML files.
Your boss walks in: "Hey, let's change the URL from /blog/archive/ to /blog/history/."
Result: You now have to find and replace that string in 50 files. You will miss one. The site will break. You will cry. 😢

The Solution: Named URLs

Never hardcode URLs. Give them a name, and ask Django to compute the URL.

1. Name the URL in urls.py

python
app_name = 'blog' # Namespacing implies this belongs to 'blog' app

urlpatterns = [
    path('post/<int:pk>/', views.post_detail, name='post_detail'),
    path('home/', views.home, name='home'),
]

2. Use in HTML Templates ({% url %})
Instead of /blog/post/1/:

html
<!-- Django looks up 'post_detail', sees it needs an integer, and builds the link -->
<a href="{% url 'blog:post_detail' pk=post.id %}">Read More</a>

3. Use in Python Views (reverse)
Sometimes you need to redirect a user after they submit a form. You can't use template tags here.

python
from django.urls import reverse
from django.http import HttpResponseRedirect

def create_post(request):
    # ... logic to save post ...
    
    # Calculate the URL string dynamically
    url = reverse('blog:post_detail', args=[new_post.id])
    return HttpResponseRedirect(url)

Why is this magical?
If you change path('post/<int:pk>/', ...) to path('article/<int:pk>/', ...) in your urls.py, you don't have to change a single line of code in your views or templates. Django updates all links automatically.


📚 References & Further Reading

Next up, we’ll look at Templates, so we can stop returning boring text and start returning beautiful HTML! 🎨

Challenge

Task

You are building the URL and View routing for a new Django blog application. Your task is to correctly structure the project and app-level urls.py files and create the corresponding view functions.

Requirements

  1. Project urls.py (myproject/urls.py):

    • Configure the URL patterns for the main project.
    • It must delegate all traffic from the blog/ path to the blog application's URL configuration using the include() function.
  2. Blog App views.py (blog/views.py):

    • Create a view named post_list that takes a request and renders the blog/post_list.html template. It should pass a context dictionary containing a key posts.
    • Create a view named post_detail_by_id that accepts a post_id (integer) from the URL. It must use get_object_or_404 to fetch a Post object by its id. It should render the blog/post_detail.html template with the fetched post in the context.
    • Create a view named post_detail_by_slug that accepts a post_slug (slug string) from the URL. It must use get_object_or_404 to fetch a Post object by its slug. It should also render the blog/post_detail.html template.
  3. Blog App urls.py (blog/urls.py):

    • Define the URL patterns for the blog app.
    • Map the app's root URL ('') to the post_list view and give it the name post_list.
    • Create a dynamic URL pattern posts/<int:post_id>/ that maps to the post_detail_by_id view. Name this pattern post_detail_id.
    • Create a dynamic URL pattern using a slug path converter (<slug:post_slug>/) that maps to the post_detail_by_slug view. Name this pattern post_detail_slug.

Fill in the missing code in the initialCode block below to meet all requirements.

Expected result

Your final code should correctly implement the URL routing and views as described. The validation will check for the following:

  1. In myproject/urls.py:

    • The urlpatterns list must contain a path() entry for blog/.
    • This entry must use include('blog.urls') to delegate routing.
  2. In blog/views.py:

    • A function post_list(request) exists and uses render() to return a response.
    • A function post_detail_by_id(request, post_id) exists.
    • post_detail_by_id must call get_object_or_404(Post, id=post_id).
    • A function post_detail_by_slug(request, post_slug) exists.
    • post_detail_by_slug must call get_object_or_404(Post, slug=post_slug).
  3. In blog/urls.py:

    • The urlpatterns list must contain exactly three path() entries.
    • A path '' mapped to views.post_list with name='post_list'.
    • A path posts/<int:post_id>/ mapped to views.post_detail_by_id with name='post_detail_id'.
    • A path <slug:post_slug>/ mapped to views.post_detail_by_slug with name='post_detail_slug'.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.