Django maps URL paths to views through URLconf modules (urls.py). Clean URLs improve SEO and readability—/articles/5/ beats /article.php?id=5.
Basic patterns
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("articles/<int:pk>/", views.detail, name="article-detail"),
]
Including app URLs
# project urls.py
path("blog/", include("blog.urls")),
Use {% url 'article-detail' pk=5 %} in templates—never hard-code paths that might change.
Important interview questions and answers
- Q: path() vs re_path()?
A:path()uses simple converters (int,slug,uuid);re_path()uses regex for complex patterns. - Q: Why name URLs?
A: Reverse resolution decouples templates and redirects from hard-coded paths—rename once in urls.py. - Q: Trailing slash convention?
A: Django defaults to APPEND_SLASH—/aboutredirects to/about/when configured.
Self-check
- What does
<int:pk>capture? - How do templates link to named URLs?
Interview prep
- Why name URLs?
Named URLs enable {% url %} and reverse() without hard-coded paths—rename once in urls.py when routes change.