Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including a querystring in a django.core.urlresolvers reverse() call

I'm trying to reverse a named URL and include a querystring in it. Basically, I've modified the login function, and I want to send ?next= in it.

Here's what I'm doing now: reverse(name) + "?next=" + reverse(redirect)

Here's what I'd like to do: reverse(name, kwargs = { 'next':reverse(redirect) } )

My URL for the login page (just as an example) looks like this:

url(r'^login/', custom_login, name = 'login'),

So how do I modify this whole thing (or call it) to include the next without having to concatenate it? It feels like an iffy solution at best.

like image 661
Brian Hicks Avatar asked Feb 14 '11 17:02

Brian Hicks


2 Answers

You can't capture GET parameters in the url confs, so your method is correct.

I generally prefer string formatting but it's the same thing.
"%s?next=%s" % (reverse(name), reverse(redirect))

http://docs.djangoproject.com/en/dev/topics/http/urls/#what-the-urlconf-searches-against

The URLconf searches against the requested URL, as a normal Python string. This does not include GET or POST parameters, or the domain name.

like image 179
Yuji 'Tomita' Tomita Avatar answered Sep 23 '22 08:09

Yuji 'Tomita' Tomita


I just made my own utility function like the one asked in the question:

from django.utils.http import urlencode  def my_reverse(viewname, kwargs=None, query_kwargs=None):     """     Custom reverse to add a query string after the url     Example usage:     url = my_reverse('my_test_url', kwargs={'pk': object.id}, query_kwargs={'next': reverse('home')})     """     url = reverse(viewname, kwargs=kwargs)      if query_kwargs:         return f'{url}?{urlencode(query_kwargs)}'      return url 
like image 28
Daniel Backman Avatar answered Sep 23 '22 08:09

Daniel Backman