I think you want to make it optional i.e. both top/
and top/1
should be accepted with one url path and one view.
You can make the URL pattern optional by adding a question mark ?
after the parameter in the URL pattern so:
path('top/(?P<pk>\d+)?/', views.top, name='top_edit'),
In this pattern, (?P<pk>\d+)?
is the optional parameter. The ?
at the end of the pattern makes the entire group optional, so that it matches either zero or one times. The (?P<pk>\d+)
part of the pattern is the regular expression for matching an integer value.
Then with this URL pattern, your view function should be able to handle both /top/
and /top/1
URLs so:
def top(request: HttpRequest, pk=None) -> HttpResponse
# when pk is None (i.e. /top/ URL)
if pk is None:
# Do something for the /top/ URL
else:
# Do something for the /top/1 URL
return render(request, 'index.html', context)
You can further see the question: Django optional URL parameters