Introduction
Django's dynamic URLs feature provides a robust mechanism to handle variable path components within your application. This documentation guides you through the essentials of mapping dynamic URLs, capturing variables, and leveraging path converters.
Mapping Dynamic URLs
# urls.py from django.urls import path from . import views urlpatterns = [ path('books/<int:book_id>/', views.book_detail, name='book_detail'), ]
# views.py from django.shortcuts import render def book_detail(request, book_id) : # Implement logic to retrieve book details using book_id # ... return render(request, 'books/book_detail.html', {'book_id': book_id})
<!-- books/templates/books/book_detail.html --> {% extends 'base.html' %} {% block content %} <h2>Book Details</h2> <p>Book ID: {{ book_id }}</p></span> <!-- Additional book details --> {% endblock %}
Path Converters
# urls.py from django.urls import path from . import views urlpatterns = [ path('authors/<str:author_name>/', views.author_profile, name='author_profile'), ]
# views.py from django.shortcuts import render def author_profile(request, author_name): # Implement logic to retrieve author profile using author_name # ...return render(request, 'authors/author_profile.html', {'author_name': author_name})
<!-- authors/templates/authors/author_profile.html --> {% extends 'base.html' %} {% block content %} <h2>Author Profile</h2> <p>Author Name: {{ author_name }}</p> <!-- Additional author details --> {% endblock %}
Conclusion
Django's dynamic URLs and path converters offer flexibility in handling various types of data within your application's URLs. The provided examples cover basic and string path converters, laying the foundation for capturing and utilizing dynamic data in your views.