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

后端 未结 5 887
一个人的身影
一个人的身影 2021-02-01 12:58

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 w

5条回答
  •  别跟我提以往
    2021-02-01 13:29

    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

    from django.utils.http import urlencode
    from django.core.urlresolvers import reverse as original_reverse
    
    def reverse(*args, **kwargs):
        get = kwargs.pop('get', {})
        url = original_reverse(*args, **kwargs)
    
        if get:
            url += '?' + urlencode(get)
    
        return url
    

    In the question's case, it can be used the following way

    from [myfunctions] import reverse
    ...
    reverse('login', get={next: reverse(redirect)})
    

提交回复
热议问题