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.
urlpatterns list structure in 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.
from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), # Home page ]
id to show different articles.from django.urls import path from .views import ArticleDetailView urlpatterns = [ path('article/<int:id>/', ArticleDetailView.as_view(), name='article_detail'), ]
urlpatterns list means no pages are connected yet.from django.urls import path from . import views urlpatterns = [] # Empty list means no URLs are defined yet
from django.urls import path, include urlpatterns = [ path('blog/', include('blog.urls')), ]
This complete example shows a simple URL pattern that connects the root URL to a function that returns a greeting.
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!'
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.
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.