How to pass GET parameters using django urlresolvers reverse ?

How to pass GET parameters using django urlresolvers reverse ?

Asked on October 26, 2018 in Django.
Add Comment


  • 4 Answer(s)

    With the url, GET parameters have nothing to do.
    Simply add it on at the end:

    url = "%s?name=joe" % reverse(viewOne)
    
    

     

    Answered on October 26, 2018.
    Add Comment

    It is more safer and more flexible way:

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

    then we can use build_url:

    url = build_url('view-name', get={'name': 'wikitechy'})
    

    which takes same arguments as reverse, but provides an extra keyword argument get where it can put the GET parameters in it as a dictionary.

    Answered on October 26, 2018.
    Add Comment

    This is very simple one:

    from django.core.urlresolvers import reverse
    from django.http import QueryDict
    def build_url(*args, **kwargs):
        params = kwargs.pop('params', {})
        url = reverse(*args, **kwargs)
        if not params: return url
     
    qdict = QueryDict('', mutable=True)
    for k, v in params.iteritems():
        if type(v) is list: qdict.setlist(k, v)
        else: qdict[k] = v
        return url + '?' + qdict.urlencode()
    

    Instance:

    build_url('member-list', params={'format': 'html', 'sex': ['male', 'female']})
    u'/members/?format=html&sex=male&sex=female'
    
    Answered on October 26, 2018.
    Add Comment

    If you need to use something similar to the url template tag in your code, Django provides the following function:

    reverse(viewnameurlconf=Noneargs=Nonekwargs=Nonecurrent_app=None)[source]

    viewname can be a URL pattern name or the callable view object. For example, given the following url:

    from news import views
    
    path('archive/', views.archive, name='news-archive')
    

    you can use any of the following to reverse the URL:

    # using the named URL
    reverse('news-archive')
    
    # passing a callable object
    # (This is discouraged because you can't reverse namespaced views this way.)
    from news import views
    reverse(views.archive)
    

    If the URL accepts arguments, you may pass them in args. For example:

    from django.urls import reverse
    
    def myview(request):
        return HttpResponseRedirect(reverse('arch-summary', args=[1945]))
    

    You can also pass kwargs instead of args. For example:

    >>> reverse('admin:app_list', kwargs={'app_label': 'auth'})
    '/admin/auth/'
    
    Answered on February 25, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.