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?
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']
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With