-1

Suppose I have this:

from django.core.urlresolvers import reverse
url = reverse('account-list')

Assume this leads to the URL: `/account/list/'

How do I add on to the URL? I want to make that URL this: /account/list/1 (adding a pk value to the end of it). I know over here: Including a querystring in a django.core.urlresolvers reverse() call it explains how to add GET parameters (e.g. ?pk=1 but I want to know if there is a proper way for me to add on to the URL (not using GET parameters)).

I'm using DRF routers: router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) and the user-detail view takes a pk value. So I want to do url = reverse('user-list') with /1 appended to the end of it.

Community
  • 1
  • 1
SilentDev
  • 20,997
  • 28
  • 111
  • 214
  • 1
    This doesn't make much sense. You can't just add random parameters in reverse - the account-list URL actually needs to accept the parameter in the first place. – Daniel Roseman Oct 24 '15 at 22:20
  • @DanielRoseman is correct. There is no reason why manual intervention to reversed urls is required in Django. However, in the end it is just a string. Add to it content, the way you would add a string. – iankit Oct 24 '15 at 22:36
  • @DanielRoseman I'm using DRF routers: `router = routers.DefaultRouter() router.register(r'users', views.UserViewSet)` and the `user-detail` view takes a `pk` value. So I want to do `url = reverse('user-list')` with `/1` appended to the end of it. – SilentDev Oct 24 '15 at 23:05
  • No, if you want to get the URL of the user-detail view you pass that name, plus the pk, to reverse, you don't try and manipulate the list URL. Why would the detail url contain "list" anyway? – Daniel Roseman Oct 24 '15 at 23:30

1 Answers1

1

If you are interested specifically in the detail view then you shouldn't use account-list. Assuming you have a separate account-detail view (Django Rest Framework will create these for you as well when you are using default ModelViewSets, just the same as it did with account-list):

from django.core.urlresolvers import reverse
u = reverse('account-detail', args=[1])

would be the proper way to go about this if I understand your question correctly.

You can also handle named URL parameters. For the following URL rule with a slug parameter:

url(r'/accounts/(?<slug>[a-fA-F0-9]+)/', name='account-detail', ...)

here's how you'd reverse the detail view for the account with a slug equal to something:

from django.core.urlresolvers import reverse
u = reverse('account-detail', kwargs={'slug': 'something'})
chucksmash
  • 5,777
  • 1
  • 32
  • 41