[Fixed]-Django redirect to another view with context

18πŸ‘

βœ…

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

31πŸ‘

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')

#jinja
{{ 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']

5πŸ‘

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

2πŸ‘

you need to use HttpResponseRedirect instead

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

0πŸ‘

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.

views.py

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

api/views.py

@api_view(['POST'])
@login_required
def messageList(request):
    data = {}
    messageList = []
    storage = messages.get_messages(request)
    for message in storage:
        msgObj = makeMessage(message.message, tag=message.level_tag)
        messageList.append(msgObj['message'])
    data['messages'] = messageList
    return Response(data)
πŸ‘€tas

0πŸ‘

What most work for me is:

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

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

Leave a comment