Home > OS >  How to use reverse with optional parameters in django?
How to use reverse with optional parameters in django?

Time:10-13

I have the below URL in which I pass an integer value (pk) now when I am calling reverse on this URL I am getting the below-mentioned error.

urls.py

    urlpatterns = [ 
path('batch-postpone/<int:pk>/', postpone_batch, name='batch-postpone'),
]

tests.py

class ABCTestCases(APITestCase, TestCase):
      self.postpone_batch_url = reverse('batch-postpone')


Error that I am getting...

django.urls.exceptions.NoReverseMatch: Reverse for 'batch-postpone' with no arguments not found. 1 pattern(s) tried: ['batch\\-postpone/(?P<pk>[0-9] )/$']



CodePudding user response:

Pass in the id in reverse() like reverse('batch-postpone', args=[1])

https://docs.djangoproject.com/en/3.2/ref/urlresolvers/#reverse

class ABCTestCases(APITestCase, TestCase):
      id = 1
      self.postpone_batch_url = reverse('batch-postpone', args=[id])

CodePudding user response:

The third paragraph of the documentation for this function.

from django.urls import reverse

def myview(request):
    return HttpResponseRedirect(reverse('arch-summary', args=[1945]))
  • Related