Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign default values to a Django path

Tags:

python

django

I am building a Django API where one of my paths in urls.py is: path('device_id/<str:device_id>/readings/<int:num_readings>, views.results, name='results')

I want to avoid getting a 404 if a user specifies a device id but does not enter a number of readings. I'd like the assign a default value of readings to 10.

This url is connect to a view called results

def results(request, device_id, readings):

For example, if a user goes to: device_id/2132/readings/ I would like device_id = 2132 and readings=10 in the results view

device_id/2132/readings/24 I would like device_id = 2132 and readings=24 in the results view

like image 867
PanczerTank Avatar asked Nov 18 '25 04:11

PanczerTank


1 Answers

Add another path where you add defaults to the kwargs, like:

urlpatterns = [
    path(
        'device_id/<str:device_id>/readings/<int:num_readings>',
        views.results,
        name='results'
    ),
    path(
        'device_id/<str:device_id>/readings/',
        views.results,
        name='results10'
        kwargs={'num_readings': 10}
    ),
    # ...
]

So here the second view is a path without a num_readings variable, but the kwargs is a dctionary that contains additional (named) parameters to pass to the view.

like image 200
Willem Van Onsem Avatar answered Nov 19 '25 19:11

Willem Van Onsem