Next

Django URL Routing

  • Learn how Django maps URLs to views using the URL routing system.
  • Why URL Routing Is Important?

    URL routing:

    • Connects browser URLs to Django views

    • Controls navigation of the website

    • Is the backbone of Request → Response cycle

    👉 Without URL routing, Django cannot show any page.

    What is URL Routing in Django?

    URL routing is the process of:

    Mapping a URL path to a view function/class

    Django checks URLs in urls.py and decides:

    • Which view should handle the request

    1. urls.py Basics

    What is urls.py?

    urls.py is the file where:

    • All URL patterns are defined

    • URLs are mapped to views

    Basic Structure of urls.py

    from django.urls import path

    from . import views

    urlpatterns = [

        path('', views.home),

    ]

    Explanation:

    • urlpatterns → List of URL rules

    • path() → Defines URL

    • views.home → View function

    Code Example: Basic URL Mapping

Basic URL Configuration

Maps home URL to a view

from django.urls import path
from django.http import HttpResponse

def home(request):
    return HttpResponse("Welcome to Django")

urlpatterns = [
    path('', home),
]
  • 2. path() vs re_path()

    Django provides two ways to define URLs:

    • path() → Simple & readable

    • re_path() → Regular expression based

    path()

    What is path()?

    path():

    • Uses simple converters

    • Easy to read & maintain

    • Most commonly used

    Code Example: path() with Parameter

URL with Path Converter

Captures dynamic URL values

from django.urls import path

def profile(request, user_id):
    return HttpResponse(f"User ID: {user_id}")

urlpatterns = [
    path('profile/<int:user_id>/', profile),
]
  • Path Converters:

    Converter

    Meaning

    int

    Integer

    str

    String

    slug

    Slug

    uuid

    UUID

    path

    Full path


    re_path()

    What is re_path()?

    re_path():

    • Uses regular expressions

    • More powerful

    • Harder to read

    • Used in advanced cases

    Code Example: re_path()

URL Using Regular Expression

Matches URL pattern using regex

from django.urls import re_path

def year_archive(request, year):
    return HttpResponse(f"Year: {year}")

urlpatterns = [
    re_path(r'^archive/(?P<year>[0-9]{4})/$', year_archive),
]
  • path() vs re_path() Comparison

    Feature

    path()

    re_path()

    Readability

    High

        Low

    Regex needed

        ✅

    Beginner friendly

        ❌

    Use case

    Most URLs

    Complex patterns

    3. include()

    What is include()?

    include() is used to:

    • Connect project URLs with app URLs

    • Keep code modular & clean

    Why include() Is Important?

    Without include():

    • All URLs go into one file

    • Code becomes messy

    With include():

    • Each app manages its own URLs

    Code Example: Using include()

Project-Level URL Configuration

Connects project URLs to app URLs

from django.urls import path, includeURL Routing
urlpatterns = [
    path('blog/', include('blog.urls')),
]

App-Level urls.py

from django.urls import path
from .views import post_list

urlpatterns = [
    path('', post_list),
]
  • URL Flow:

    /blog/ → project urls → app urls → view

    4. Named URLs (Best Practice)

    Why Name URLs?

    • Avoid hardcoding URLs

    • Easy to change later

    • Required for templates

    Code Example: Named URL

URL Naming

Assigns name to URL

path('login/', views.login_view, name='login')
  • Using Named URL in Template

    <a href="{% url 'login' %}">Login</a>

    5. Common Beginner Mistakes

    Mistake

    Fix

    View not called

    Check URL path

    404 error

    Check include()

    Wrong parameter type

    Match converter

    Regex error

    Prefer path()

Next