[Fixed]-Django redirect to another view with context



In django You can not pass parameters with redirect. Your only bet is to pass them as a part of URL.

def foo(request):
    redirect(reverse('app:view', kwargs={ 'bar': FooBar }))

in your html you can get them from URL.

πŸ‘€Ojas Kale


I would use session variables in order to pass some context through a redirect. It is about the only way to do it outside of passing them as part of the url and it is the recommended django option.

def foo(request):
    request.session['bar'] = 'FooBar'
    return redirect('app:view')

{{ request.session.bar }}

A potential pitfall was pointed out, whereas the session variable gets used incorrectly in a future request since it persists during the whole session. If this is the case you can fairly easily circumvent this problem in a future view in the situation it might be used again by adding.

if 'bar' in request.session:
    del request.session['bar']


I was with the same problem. I would like to redirect to another page and show some message, in my case, it’s a error message. To solve it, I used the django messages: https://docs.djangoproject.com/en/4.0/ref/contrib/messages/

I did this:

    def foo(request):
        message.error(request, 'bla bla bla')
        return redirect('foo_page')

In my template foo_page.html:

    {% if messages %}
       {% for message in messages %}
       <div class={{ message.tags }}>{{ message }}</div>
       {% endfor %}
    {% endif %}
πŸ‘€JG G


you need to use HttpResponseRedirect instead

from django.http import HttpResponseRedirect
return HttpResponseRedirect(reverse('app:view', kwargs={'bar':FooBar}))


I just had the same issue, and here is my solution.

I use Django messages to store my parameter.

In template I do not read it with template tag {% for message in messages %}, but rather do POST request to my API to check if there are any messages for me.


def foo(request):
    messages.success(request, 'parameter')
    return redirect('app:view')


def messageList(request):
    data = {}
    messageList = []
    storage = messages.get_messages(request)
    for message in storage:
        msgObj = makeMessage(message.message, tag=message.level_tag)
    data['messages'] = messageList
    return Response(data)


What most work for me is:

 next_url = '/'
 url = reverse('app:view')

 url = f'{url}?next={next_url}&'
 return redirect (url)

Leave a comment