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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With