Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django redirect to another view with context

I have this in my view

def foo(request):

    context['bar'] = 'FooBar'

    return redirect('app:view')

is there some way to include this context['bar'] when I redirect to 'app:view'? My last resort and alternative would be to do use render() however, I do not want to define all the context variables again. Is there any other approach to this?

like image 813
JM Lontoc Avatar asked Jul 03 '18 13:07

JM Lontoc


2 Answers

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']
like image 60
Mitchell Walls Avatar answered Oct 10 '22 16:10

Mitchell Walls


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

def foo(request):

    context['bar'] = 'FooBar'

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

in your html you can get them from URL.

like image 31
Ojas Kale Avatar answered Oct 10 '22 16:10

Ojas Kale