Python Tutorial
Django URLs
URL patterns connect a path in the browser to a view function. Create an app urls.py and include it from the project.
Create members/urls.py
This file does not exist until you add it:
# members/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.members, name="members"),
]name="members" lets templates and views reverse this URL later with {% url "members" %} instead of hard-coding /members/.
Include the App in the Project
Open mysite/urls.py:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("members/", include("members.urls")),
path("admin/", admin.site.urls),
]Now http://127.0.0.1:8000/members/ calls views.members and shows Hello world!.
Path Converters
Capture values from the URL and pass them as view arguments:
path("details/<int:id>/", views.details, name="details")def details(request, id):
return HttpResponse(f"Member id: {id}")| Converter | Matches |
|---|---|
str | Any non-empty string except / |
int | Positive integers |
slug | Letters, numbers, hyphens, underscores |
uuid | A UUID |
Trailing Slashes
Django's default APPEND_SLASH redirects /members to /members/. Define patterns with a trailing slash to match that convention.
📘 Real-World Deep Dive
Knowing <strong>Django Urls (Django)</strong> well is what turns Django from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of Django Urls that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
# mysite/urls.py
from django.urls import path, include
urlpatterns = [
path("pages/", include("pages.urls")),
path("admin/", admin.site.urls),
]Expected Output
(no output)Common mistakes
- Forgetting to call
.save()on a model instance after mutation silently persists nothing. - Reading every row with
Model.objects.all()on a 1 M-row table OOMs the worker — use.iterator()for streaming. - Queries inside loops produce N+1 problems — pull related rows with
select_related/prefetch_related. - Treating Django Urls as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- Add database indexes (
db_index=TrueorMeta.indexes) on columns used infilter. - Use
cache_pageon read-heavy views and setCONN_MAX_AGEto keep DB connections warm. - Generate migrations with
python manage.py makemigrations --dry-run --verbosity 3and review before committing. - When working with Django, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.