Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework reverse and SimpleRouter

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
like image 513
YPCrumble Avatar asked Mar 03 '15 00:03

YPCrumble


People also ask

What is reverse in Django REST Framework?

reverse. Has the same behavior as django. urls. reverse , except that it returns a fully qualified URL, using the request to determine the host and port.

What is Basename in Django REST Framework?

basename - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the queryset attribute of the viewset, if it has one. Note that if the viewset does not include a queryset attribute then you must set basename when registering the viewset.

Can I use Django and Django REST Framework together?

Django Rest Framework makes it easy to use your Django Server as an REST API. REST stands for "representational state transfer" and API stands for application programming interface. Note that with DRF you easily have list and create views as well as authentication.

Is Django REST Framework synchronous?

Django REST framework is built on Django, which is a synchronous framework for web applications. If you're already using a synchronous framework like Django, having a synchronous API is less of an issue.


1 Answers

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'
)
like image 184
Aaron Lelevier Avatar answered Sep 21 '22 16:09

Aaron Lelevier