[Django]-How to assign default values to a Django path

4👍

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.

2👍

What about specifying a default for readings in your view:

def results(request, device_id="", readings=10):
    # ...

and write urls like (use re_path in order to use regular expression to state that num_readings is optional):

urlpatterns = [
    re_path(
        'device_id/(?P<device_id>\w+)/readings/(?P<num_readings>\d+)?',
        views.results,
        name='results'
    ),
   # ...
]

Leave a comment