0
0
Djangoframework~5 mins

path function for routes in Django

Choose your learning style9 modes available
Introduction

The path function helps Django know which code to run when someone visits a web address on your site.

When you want to connect a web address to a specific page or action in your Django app.
When you need to organize different pages of your website with clear URLs.
When you want to handle user requests like showing a list, details, or forms.
When you want to add simple or dynamic parts to your URLs, like user IDs.
When setting up the main navigation routes of your Django project.
Syntax
Django
path(route, view, name=None)

route is the URL pattern as a string, like 'home/' or 'blog//'.

view is the function or class that runs when the URL is visited.

name is an optional label to refer to this route elsewhere.

Examples
Connects the URL ending with 'home/' to the home_view function and names it 'home'.
Django
path('home/', views.home_view, name='home')
Matches URLs like 'article/5/' and passes the number 5 as id to the view.
Django
path('article/<int:id>/', views.article_detail, name='article-detail')
Matches the root URL (no extra path) and runs the index view.
Django
path('', views.index, name='index')
Sample Program

This example shows three routes: the home page, an about page, and a product detail page that takes a product ID from the URL.

Django
from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('about/', views.about, name='about'),
    path('product/<int:id>/', views.product_detail, name='product-detail'),
]

# views.py
from django.http import HttpResponse

def home(request):
    return HttpResponse('Welcome to the Home Page')

def about(request):
    return HttpResponse('About Us Page')

def product_detail(request, id):
    return HttpResponse(f'Product Details for product id: {id}')
OutputSuccess
Important Notes

Always end your URL patterns with a trailing slash for consistency.

Use name to easily refer to URLs in templates and redirects.

Dynamic parts like <int:id> let you capture values from the URL.

Summary

The path function connects URLs to code that runs when those URLs are visited.

You can use simple strings or dynamic parts in the URL pattern.

Giving routes a name helps you manage URLs easily in your project.