[Django]-How to redirect with a get parameter in django view?

1πŸ‘

βœ…

To the best of my knowledge, Django has no tooling to add querystrings to an URL, but that is not per se a problem, since we can make our own function, for example:

from django.urls import reverse
from django.http.response import HttpResponseRedirect

def redirect_qd(viewname, *args, qd=None, **kwargs):
    rev = reverse(viewname, *args, **kwargs)
    if qd:
        rev = '{}?{}'.format(rev, qd.urlencode())
    return HttpResponseRedirect(rev)

Encoding the values is important. Imagine that your group has as value foo&bar=3. If you do not encode this properly, then this means that your querystring will later be parsed as two parameters: group and bar with group being foo and bar being 3. This is thus not what you intended. By using the urlencode, it will result in 'group=foo%26bar%3D3', which thus is the intended value.

and then we can use this function like:

from django.http.request import QueryDict

def product_new(request):
    group = request.GET.get('group')
    if group == None:
        product = Product.objects.create()
        return redirect('cms:product_list_edit')
    else:
        product = Product.objects.create(group=group)
        qd = QueryDict(mutable=True)
        qd.update(group=group)
        return redirect_qd('cms:product_list_edit', qd=qd)

If you simply want to pass the entire querystring, you can thus call it with redirect_qd('myview', request.GET).

3πŸ‘

for python3 and above:

def redirect_with_params(viewname, **kwargs):
    """
    Redirect a view with params
    """
    rev = reverse(viewname)

    params = urllib.parse.urlencode(kwargs)
    if params:
        rev = '{}?{}'.format(rev, params)

    return HttpResponseRedirect(rev)

use:

redirect_with_params('main-domain:index', param1='value1', param2='value2')
πŸ‘€juan Isaza

1πŸ‘

I found the answer exactly what I wanted.

def product_new(request):
    group = request.GET.get('group')
    if group == None:
        product = Product.objects.create()
        return redirect('cms:product_list_edit')
    else:
        product = Product.objects.create(group=group)
        response = redirect('cms:product_list_edit')
        response['Location'] += '?group=' + group
        return response
πŸ‘€Jeongyong Lee

Leave a comment