← Back to Chapters

path() and re_path() Functions

? path() and re_path() Functions

? Quick Overview

In Django, URL routing is managed using the path() and re_path() functions, which map URLs to views. These functions are used in the urls.py files to define URL patterns for your project and app.

? Key Concepts

  • URL dispatcher connects browser requests to Django views
  • path() uses simple readable patterns
  • re_path() uses regular expressions

? Syntax & Theory

? path() Function

The path() function is used to define URL patterns that are simple and readable.

? View Code Example
// Basic syntax of path() function
path('url_pattern/', view_function, name='url_name')

Example of Using path()

? View Code Example
// Defining simple URL routes using path()
from django.urls import path
from . import views

urlpatterns = [
path('home/', views.home, name='home'),
path('about/', views.about, name='about'),
]

? re_path() Function

The re_path() function is used for complex URL patterns that require regular expressions.

? View Code Example
// Basic syntax of re_path() with regex
re_path(r'url_pattern/', view_function, name='url_name')

Example of Using re_path()

? View Code Example
// URL pattern capturing numeric ID using regex
from django.urls import re_path
from . import views

urlpatterns = [
re_path(r'^post/(?P<id>\d+)/$', views.post_detail, name='post_detail'),
]

? Live Output / Explanation

What Happens?

When a user visits /post/5/, Django extracts the number 5 and passes it as an argument to the post_detail view function.

? Interactive Understanding

Try changing the number in the URL (e.g. /post/10/) and observe how Django dynamically routes the request.

? URL Simulator

Matched Pattern: None

Extracted Data: N/A

Type a URL to see how it resolves.

? Use Cases

  • Static pages like Home, About, Contact using path()
  • Blog posts, user profiles, product pages using re_path()
  • APIs with strict URL formats

✅ Tips & Best Practices

  • Prefer path() for readability
  • Use re_path() only when regex is required
  • Keep URL patterns clean and predictable

? Try It Yourself

  • Create a blog app with post detail URLs
  • Capture usernames using regex
  • Test multiple URL formats