Reputation: 167
I have a url path that looks like this:
path("asset_app/asset/<str:location>/", views.AssetListView.as_view(), name="asset_app_asset_list"),
I want that if location is not set that it sets
location = "all"
How do I do that?
Upvotes: 1
Views: 1429
Reputation: 10709
Use regex with django.urls.re_path to capture an optional field location
within the URL. Then, define its default value in the view.
urls.py
from django.urls import re_path
from my_app.views import get_asset
urlpatterns = [
re_path(r"asset_app/asset/(?P<location>\w+)?", get_asset),
]
views.py
from django.http import HttpResponse
def get_asset(request, location="all"):
print(f"{location=}")
return HttpResponse(location)
Output:
$ curl http://127.0.0.1:8000/asset_app/asset/
all
$ curl http://127.0.0.1:8000/asset_app/asset/whatever
whatever
$ curl http://127.0.0.1:8000/asset_app/asset/wherever/
wherever
Logs:
location='all'
[04/Aug/2021 07:40:27] "GET /asset_app/asset/ HTTP/1.1" 200 3
location='whatever'
[04/Aug/2021 07:40:40] "GET /asset_app/asset/whatever HTTP/1.1" 200 8
location='wherever'
[04/Aug/2021 07:42:00] "GET /asset_app/asset/wherever/ HTTP/1.1" 200 8
Related reference:
Upvotes: 3
Reputation: 931
Any how in this case as suggested by @bdbd you have to use 2 url patterns one with location argument and other without it which will point to same view like below:
path("asset/<str:location>/", views.AssetListView.as_view(),name="asset_app_asset_list"),
path("asset/", views.AssetListView.as_view(),name="asset_app_asset_withoutlist"),
In your CBV you can access location by get method on kwargs with default value as 'all' if not passed as arguments in url:
location = self.kwargs.get('location','all')
Upvotes: 1