2

I want to accept both urls with and without parameters, such as /top/ /top/1

I tried a few patterns:

path('top/<int:pk>/', views.top, name='top_edit'),
path('top/(<int:pk>)/', views.top, name='top_edit'),
path('top/(<int:pk>)/$', views.top, name='top_edit'),


def top(request: HttpRequest,pk = None) -> HttpResponse:
    return render(request, 'index.html', context)

It accept /top/1 however /top/ is not accepted.

How can I make it work?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
whitebear
  • 11,200
  • 24
  • 114
  • 237

3 Answers3

0

Instead of pk = None in view Try this,

def top(request: HttpRequest,pk = '') -> HttpResponse:
    return render(request, 'index.html', context)
ilyasbbu
  • 1,468
  • 4
  • 11
  • 22
0

You need to define the URL without the parameter too:

path('top/<int:pk>/', views.top, name='top_edit'),
path('top/(<int:pk>)/', views.top, name='top_edit'),
path('top/(<int:pk>)/$', views.top, name='top_edit'),
path('top/', views.top, name='top'),


def top(request: HttpRequest,pk = None) -> HttpResponse:
    return render(request, 'index.html', context)
Boketto
  • 707
  • 7
  • 17
0

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

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40