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

后端 未结 5 808
一个人的身影
一个人的身影 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:31

    I think it's better to wrap Django's reverse method to expose this API. Here's some simple code to do it:

    from django.core.urlresolvers import reverse as django_reverse
    
    def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None):
        """
        Wrapper of django.core.urlresolvers.reverse that attaches arguments in kwargs as query string parameters
        """
        if kwargs:
            return '%s?%s' % (django_reverse(viewname, urlconf, args, None, prefix, current_app), \
                            '&'.join(['%s=%s' % (k,v) for k,v in kwargs.items()]))
        else:
            return django_reverse(viewname, urlconf, args, kwargs, prefix, current_app)
    

    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

提交回复
热议问题