Django maps URLs to views via urlpatterns.
Basic Syntax
# tasks/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.task_list, name='task-list'),
path('<int:pk>/', views.task_detail, name='task-detail'),
path('create/', views.create_task, name='task-create'),
path('<int:pk>/edit/', views.edit_task, name='task-edit'),
path('<int:pk>/delete/', views.delete_task, name='task-delete'),
]
path() Converters
path('<int:pk>/', view) # integer → pk
path('<str:slug>/', view) # string → slug
path('<uuid:id>/', view) # UUID
path('<slug:slug>/', view) # slug (letters, digits, hyphens)
name= — Named URLs
path('tasks/', views.task_list, name='task-list')
In a template:
<a href="{% url 'task-list' %}">All Tasks</a>
<a href="{% url 'task-detail' pk=task.pk %}">Task #{{ task.pk }}</a>
In Python:
from django.urls import reverse
url = reverse('task-detail', kwargs={'pk': 5}) # '/tasks/5/'
redirect('task-list')
include() — Connecting Application URLs
# mysite/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('tasks/', include('tasks.urls')),
path('blog/', include('blog.urls')),
path('api/', include('api.urls')),
]
Namespace — URL Namespacing
# tasks/urls.py
app_name = 'tasks' # ← add this
urlpatterns = [
path('', views.task_list, name='list'),
path('<int:pk>/', views.task_detail, name='detail'),
]
In a template:
{% url 'tasks:list' %}
{% url 'tasks:detail' pk=task.pk %}
re_path — Regular Expressions (rarely needed)
from django.urls import re_path
urlpatterns = [
re_path(r'^archive/(?P<year>[0-9]{4})/$', views.archive),
]
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!