Search code examples
djangohttp-redirectparametersget

How to redirect with a get parameter in django view?


I want to redirect with a GET parameter in django view. I want to use GET parameter for some reasons, not url parameter.

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)
        rreturn redirect('cms:product_list_edit') # I want to redirect this url with GET parameter.

Solution

  • 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).