Django
URL Routing
Wire URLs to views with path converters and includes.
By EZ4Code Team
urlsrouting
Code
# project/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("admin/", admin.site.urls),
path("articles/", include("articles.urls")),
path("api/", include("api.urls")),
]
# articles/urls.py
from django.urls import path
from . import views
app_name = "articles"
urlpatterns = [
path("", views.ArticleListView.as_view(), name="list"),
path("<int:pk>/", views.ArticleDetailView.as_view(), name="detail"),
path("create/", views.ArticleCreateView.as_view(), name="create"),
]Explanation
path() maps a URL pattern to a view, while include() delegates a prefix to another app's urls module. Path converters like <int:pk> capture typed segments passed as kwargs to the view. Naming URLs with name and app_name enables reverse() and the {% url %} template tag.
More Django Snippets
Model Definition
Define a Django model with field types and meta options.
ORM QuerySet
Filter, exclude, annotate and chain QuerySets.
Class-Based Views
Use generic class-based views for common CRUD flows.
ModelForms
Build forms from models with validation and widgets.
Template Tags
Use built-in tags and filters in Django templates.
Admin Customization
Customize the Django admin with list_display and actions.