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.
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']
- How to create a 8 digit Unique ID in Python?
- Variable not found. Declare it as envvar or define a default value
- Using existing field values in django update query
- Django Building a queryset with Q objects
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 %}
- Django time difference with F object
- Multiple User Types For Auth in Django
- Django: Override Debug=True from manage.py runserver command
- Does Django have BDD testing tools comparable to Rails' testing tools?
2π
you need to use HttpResponseRedirect
instead
from django.http import HttpResponseRedirect
return HttpResponseRedirect(reverse('app:view', kwargs={'bar':FooBar}))
- Does a library to prevent duplicate form submissions exist for django?
- Adding a "through" table to django field and migrating with South?
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)
0π
What most work for me is:
next_url = '/'
url = reverse('app:view')
url = f'{url}?next={next_url}&'
return redirect (url)