26๐
Please note the answer suggested here is only applicable to Django < 1.2:
Do you have control over the view that you are redirecting to? In that case you can save the context in the session before redirecting. The target view can pick up the context (and delete it) from the session and use it to render the template.
If your only requirement is to display a message then there is a better way to do this. Your first view can create a message for the current using auth
and have the second view read and delete it. Something like this:
def save_form(request, *args, **kwargs):
# all goes well
message = _("form for customer xyz was successfully updated...")
request.user.message_set.create(message = message)
return redirect('list_view')
def list_view(request, *args, **kwargs):
# Render page
# Template for list_view:
{% for message in messages %}
...
{% endfor %}
Messages are saved to the database. This means that you can access them even after a redirect. They are automatically read and deleted on rendering the template. You will have to use RequestContext
for this to work.
For Django => 1.2 read the answer involving messages
83๐
request.user.message_set
was deprecated in Django 1.2 and has been removed since Django 1.4, the message framework should be used instead.
from django.contrib import messages
# messages.add_message(request, level, message, extra_tags='', fail_silently=False)
messages.add_message(request, messages.INFO, "Your Message")
Alternatively, you can use one of the shortcut functions:
from django.contrib import messages
messages.debug(request, "Your Message")
messages.info(request, "Your Message")
messages.success(request, "Your Message")
messages.warning(request, "Your Message")
messages.error(request, "Your Message")
Messages can then be rendered on the template with:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
- [Django]-How to stream an HttpResponse with Django
- [Django]-Convert an IP string to a number and vice versa
- [Django]-Raise a validation error in a model's save method in Django
15๐
To expand on Antoineโs helpful answer: if you want to process the messages in your views module, rather than the template:
from django.contrib.messages import get_messages
def my_view(request):
# Process your form data from the POST, or whatever you need to do
# Add the messages, as mentioned above
messages.add_message(request, messages.INFO, form.cleaned_data['name'])
return HttpResponseRedirect('/other_view_url/')
def other_view(request):
storage = get_messages(request)
name = None
for message in storage:
name = message
break
return render(request, 'general/other_view.html', {'name': name})
- [Django]-How does django handle multiple memcached servers?
- [Django]-ImportError: cannot import name 'url' from 'django.conf.urls' after upgrading to Django 4.0
- [Django]-Django REST Framework (DRF): Set current user id as field value
1๐
I found the following to work if more than just a message needs to be added to the redirect:
from django.shortcuts import redirect
import urllib
def my_view(request):
...
context = {'foo1': bar1, 'foo2': bar2, 'foo3': bar3}
return redirect('/redirect_link/?' + urllib.parse.urlencode(context))
See also
how to pass context data with django redirect function?
- [Django]-Django model blank=False does not work?
- [Django]-Django Rest Framework, passing parameters with GET request, classed based views
- [Django]-ReactJS with Django โ real usage
1๐
In Django 2.x + you can simply use messages framework that comes with Django
views.py
from django.contrib import messages
def register(request):
....
messages.success(request,"You have registered successfully, now login!")
return redirect('login-page')
And in you, login.html template do add this code
{% if messages %}
{% for message in messages %}
<div class="alert alert-success alert-dismissible fade show">
<strong>Success!</strong> {{message}}
<button type="button" class="close" data-dismiss="alert">×</button>
</div>
{% endfor %}
{% endif %}
Note this example can be applied to anywhere you want to display a message for success
If you want to pass an error message simply use messages.error(request, "Error message")
- [Django]-Populating django field with pre_save()?
- [Django]-How do I use a dictionary to update fields in Django models?
- [Django]-Auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'UserManage.groups'
0๐
To Django Admin, I could redirect with the several types of messages as shown below:
# "views.py"
from django.contrib import messages # Here
from django.shortcuts import redirect
def my_view(request):
messages.debug(request, 'This is debug')
messages.info(request, 'This is info')
messages.success(request, 'This is success')
messages.warning(request, 'This is warning')
messages.error(request, 'This is error')
return redirect("http://localhost:8000/admin/store/order/")
But, I donโt know why only "debug" message is not displayed even though "DEBUG = True" in "settings.py":
- [Django]-Manage.py runserver
- [Django]-Django template tag to truncate text
- [Django]-Django: Fat models and skinny controllers?