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?

2
  • 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 Commented Aug 4, 2021 at 7:14
  • 1
    check this stackoverflow.com/a/20318971/8401179 Commented Aug 4, 2021 at 7:36

2 Answers 2

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:

Sign up to request clarification or add additional context in comments.

Comments

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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.