Adam
Adam

Reputation: 2552

Specify two arguments in URL parameters for path Django

I've currently got an endpoint that accepts GET requests, to retrieve users within a date range (there's no real need to explain the 'why'). The specific endpoint looks like this: GET /users/?fromdate={yyyy-mm-dd}&todate={yyyy-mm-dd}

For example, I can have a request such as: GET /users/?fromdate=2017-01-01&todate=2017-04-01

Without going too much into detail on the urls.py and views.py, I've specified the router register and path to accept requests to this endpoint (which works fine):

urls.py:

router = routers.DefaultRouter()
router.register(r"user", views.UserViewSet, basename='user')

urlpatterns = [
    path('user/', views.UserViewSet.as_view({'get': 'user'}), name='user')
]

I am now trying to run a unit test just to send a request to this endpoint

Part of my test_user.py class looks like this:

def test_user_list(self):
    response = self.client.get(reverse('user', kwargs={'fromdate': '2017-01-01', 'todate': '2017-04-01'})), format='json')
    self.assertEqual(response.status_code, 200)

However, when I run the unit test, I get an error:

Reverse for 'user' with keyword arguments '{'fromdate': '2017-01-01', 'todate': '2017-04-01'}' not found. 1 pattern(s) tried: ['/user/$']

I think the error is due to the fact that my path (while it works manually through a REST client like Postman) doesn't specify the arguments to expect path('user/', views.UserViewSet.as_view({'get': 'user'}), name='user')

So how do I specify the arguments to satisfy a 'fromdate' and 'todate' as above? I have had a look at the documentation but I couldn't find anything other than urls such as /articles/2005/03/ for example.

Upvotes: 1

Views: 505

Answers (1)

Tim Nyborg
Tim Nyborg

Reputation: 1649

kwargs, when passed to reverse(), become URL args, e.g. user/arg1/arg2/

If you want to pass URL vars, the kwargs should be passed to .get() instead, as data:

response = self.client.get(reverse('user'), {'fromdate': '2017-01-01', 'todate': '2017-04-01'})

Upvotes: 3

Related Questions