how to redirect to a url with query string django

后端 未结 4 1021
星月不相逢
星月不相逢 2020-12-31 06:16

AoA, How can I goto a specific URL with parameters like if I have view

def search(request):

and in urls.py

^search/$ 
         


        
相关标签:
4条回答
  • 2020-12-31 06:46

    To redirect to another page while carrying along the the current query strings:

    views.py:

    from django.urls import reverse
    from django.shortcuts import redirect
    
    def my_view(request):
        #get the current query string
        q = request.META['QUERY_STRING']
        return redirect(reverse('search_view') + '?' + q)
    
    0 讨论(0)
  • 2020-12-31 06:50

    the answer is pretty simple. Using reverse and passing name of url can redirect to url with query string

    urls.py

    url(r'^search/$', views.search, name='search_view')
    

    views.py

    from django.shortcuts import redirect, reverse
    
    # in method
    return redirect(reverse('search_view') + '?item=4')
    
    0 讨论(0)
  • 2020-12-31 06:50

    I know this question is a bit old, but someone will stumble upon this while searching redirect with query string, so here is my solution:

    import urllib
    from django.shortcuts import redirect
    
    def redirect_params(url, params=None):
        response = redirect(url)
        if params:
            query_string = urllib.urlencode(params)
            response['Location'] += '?' + query_string
        return response
    
    def your_view(request):
        your_params = {
            'item': 4
        }
        return redirect_params('search_view', your_params)
    
    0 讨论(0)
  • 2020-12-31 06:54

    A more generic option;

    from urllib.parse import urlencode
    from django.shortcuts import redirect as django_redirect
    
    
    def redirect(url, *args, params=None, **kwargs):
        query_params = ""
        if params:
            query_params += '?' + urlencode(params)
        return django_redirect(url+query_params, *args, **kwargs)
    
    
    0 讨论(0)
提交回复
热议问题