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.
I was troubled with the same question and found this link. Apparently, your solution isn't bad designed at all. According to the ticket discussion Django won't provide this functionality.
You could use urlobject or furl.
The other way, is to use your own function to do this, in a much more cleaner way. Here's the one stated in the discussion
In the question's case, it can be used the following way
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
I think it's better to wrap Django's reverse method to expose this API. Here's some simple code to do it:
Put this code into some utility or common app that only depends on Django, then instead of importing django.core.urlresolvers.reverse just import myproject.myutils.urlresolvers.reverse
To keep the query optional, you can wrap Django's reverse function with your own function that also handles the query, allowing for other proper handling of the reverse function.
Creating a Proper Request - Note that the
query_kwargs
is optional, so you don't have to send itIn
utils.py
file (based on docs) for (1.11 and up?)In the urls conf
urls.py
And gaining access to the query
I just made my own utility function like the one asked in the question: