1

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?

Reventlow
  • 147
  • 1
  • 10
  • 1
    I don't think this is possible with just one url. You will have to create another url for just `asset_app/asset/` but uses the same view. And then in your view, make the `location` kwarg optional with `all` as default – Brian Destura Aug 04 '21 at 07:14
  • 1
    check this https://stackoverflow.com/a/20318971/8401179 – SANGEETH SUBRAMONIAM Aug 04 '21 at 07:36

2 Answers2

3

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:

1

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')
Ashish Nautiyal
  • 861
  • 6
  • 8