0
0
Djangoframework~5 mins

urlpatterns list structure in Django

Choose your learning style9 modes available
Introduction

The urlpatterns list tells Django which web pages to show for different website addresses. It connects web addresses to the code that shows the page.

When you want to make a new page on your website.
When you want to connect a web address to a specific function or page.
When you want to organize your website's pages in a clear way.
When you want to add links to other apps inside your Django project.
When you want to handle errors or special pages like login or logout.
Syntax
Django
from django.urls import path

urlpatterns = [
    path('url-pattern/', view_function, name='url_name'),
    path('another-url/', AnotherView.as_view(), name='another_name'),
]

The urlpatterns is a Python list that holds all the URL patterns.

Each path() connects a URL pattern to a view function or class.

Examples
This example shows the home page URL pattern with an empty string for the root URL.
Django
from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),  # Home page
]
This example uses a dynamic URL with an integer parameter id to show different articles.
Django
from django.urls import path
from .views import ArticleDetailView

urlpatterns = [
    path('article/<int:id>/', ArticleDetailView.as_view(), name='article_detail'),
]
An empty urlpatterns list means no pages are connected yet.
Django
from django.urls import path
from . import views

urlpatterns = []  # Empty list means no URLs are defined yet
This example shows how to include URL patterns from another app called 'blog'.
Django
from django.urls import path, include

urlpatterns = [
    path('blog/', include('blog.urls')),
]
Sample Program

This complete example shows a simple URL pattern that connects the root URL to a function that returns a greeting.

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

# Simple view function

def hello_world(request):
    return HttpResponse('Hello, world!')

urlpatterns = [
    path('', hello_world, name='home'),
]

# To test this, run Django server and visit http://localhost:8000/ to see 'Hello, world!'
OutputSuccess
Important Notes

The urlpatterns list is checked in order from top to bottom to find a matching URL.

Time complexity is generally fast because Django uses efficient matching behind the scenes.

Common mistake: forgetting to import the view or misspelling the URL pattern.

Use include() to keep URLs organized when your project grows.

Summary

urlpatterns is a list that connects website addresses to code that shows pages.

Use path() to add each URL pattern with a view function or class.

Keep your URLs organized by including other URL lists from apps.