Django Rest Framework reverse and SimpleRouter

YPCrumble picture YPCrumble · Mar 3, 2015 · Viewed 13.6k times · Source

How do I use DRF's reverse to call a complex URL from SimpleRouter?

My URL is at two places, one for teams, and one for games, as follows:

league.urls:

url(r'^team/', include('teams.urls')),

team.urls:

router = SimpleRouter()
router.register(r'game', GameViewSet, 'games')

I'm trying to reverse the url to update a game. Based on the DRF SimpleRouter, this should be "/team/{pk}/game/{pk}"

My test is calling:

url = reverse('games-detail', args=[team.pk, game.pk])

But I'm getting the following error:

    raise error, v # invalid expression
error: redefinition of group name u'pk' as group 2; was group 1

Answer

Aaron Lelevier picture Aaron Lelevier · Mar 3, 2015

YPCrumble, you would want to call the URL with distinct kwargs. The URL regex works in a way to handle kwargs. So for example:

# python reverse url
url = reverse('games-detail', kwargs={'team_pk': 1, 'group_pk':1})

# url regex
url(
    r'^team/(?P<team_pk>\d+)/group/(?P<group_pk>\d+)/$',
    view.SimpleRouterDetailView.as_view(),
    name='games-detail'
)