django route accept params with character
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('products/<str:category>/', views.products_by_category, name='products_by_category'),
]
# views.py
from django.shortcuts import render
from django.http import HttpResponse
def products_by_category(request, category):
return HttpResponse(f'Products in the {category} category')
Explanation:
1. In the urls.py
file, a URL pattern is defined using Django's path
function.
2. The path is set to 'products/<str:category>
defines a URL parameter named 'category' that accepts a string.
3. This URL pattern will match any URL starting with 'products/' followed by a string value for the 'category' parameter.
4. The URL pattern is linked to the products_by_category
view function.
5. In the views.py
file, the products_by_category
function takes two parameters: request
and category
.
6. The category
parameter corresponds to the value captured from the URL.
7. Inside the products_by_category
function, an HTTP response is generated, displaying a message indicating the category extracted from the URL.
8. When a user accesses a URL like '/products/books/', the 'books' string will be captured as the 'category' parameter and displayed in the response message.