Django URL Routing Patterns and Reverse Resolution Techniques

URL Routing Patterns

Django provides flexible URL routing through regular expressions:

# Basic URL pattern
url(r'^articles/$', views.article_list),

# Homepage pattern
url(r'^$', views.homepage),

# Django 2.x+ syntax
path('admin/', admin.site.urls),
re_path(r'^articles/$', views.article_list)

Unnamed and Named Groups

Unnnamed groups capture positional argumetns:

url(r'^articles/(\d+)/$', views.article_detail)
# Captures number as positional arg to view

Named groups capture keyword arguments:

url(r'^articles/(?P<year>\d+)/(?P<month>\d+)/$', views.monthly_archive)
# Captures as kwargs: {'year':..., 'month':...}

Reverse URL Resolution

Basic reverse resolution:

# urls.py
url(r'^about/$', views.about, name='about_page')

# views.py
from django.urls import reverse
url = reverse('about_page')  # '/about/'

# template
<a href="{% url 'about_page' %}">About Us</a>

Reverse with groups:

# Unnamed group reverse
url(r'^products/(\d+)/$', views.product, name='product_detail')
reverse('product_detail', args=(123,))  # '/products/123/'

# Named group reverse
url(r'^products/(?P<id>\d+)/$', views.product, name='product_detail')
reverse('product_detail', kwargs={'id': 123})  # '/products/123/'

URL Routing Distribution

Split routes across apps for better organization:

# project/urls.py
from django.conf.urls import include

urlpatterns = [
    url(r'^blog/', include('blog.urls')),
    url(r'^shop/', include('ecommerce.urls'))
]

Namespace Implementation

# project/urls.py
url(r'^blog/', include('blog.urls', namespace='blog')),

# Usage
reverse('blog:post_detail', args=(42,))

URL Pattern Difefrences in Django Versions

  1. Django 1.x uses url() with regex support
  2. Django 2.x introduces:
    • path() for simple patterns
    • re_path() for regex patterns
    • Path converters (int, str, uuid, etc.)

Table Relationship Syntax

# Django 1.x
models.ForeignKey('Model')

# Django 2.x+
models.ForeignKey('Model', on_delete=models.CASCADE)

Tags: Django URL routing Reverse Resolution web development python

Posted on Mon, 01 Jun 2026 16:50:06 +0000 by isurgeon