12đź‘Ť
This is a built-in feature of Django, called “messages”
See http://docs.djangoproject.com/en/dev/topics/auth/#messages
From the documentation:
A message is associated with a User.
There’s no concept of expiration or
timestamps.Messages are used by the Django admin
after successful actions. For example,
“The poll Foo was created
successfully.” is a message.
8đź‘Ť
You can use django-flashcookie app
http://bitbucket.org/offline/django-flashcookie/wiki/Home
it can send multiple messages and have unlimited types of messages. Lets say you want one message type for warning and one for error messages, you can write
def simple_action(request):
...
request.flash['notice'] = 'Hello World'
return HttpResponseRedirect("/")
or
def simple_action(request):
...
request.flash['error'] = 'something wrong'
return HttpResponseRedirect("/")
or
def simple_action(request):
...
request.flash['notice'] = 'Hello World'
request.flash['error'] = 'something wrong'
return HttpResponseRedirect("/")
or even
def simple_action(request):
...
request.flash['notice'] = 'Hello World'
request.flash['notice'] = 'Hello World 2'
request.flash['error'] = 'something wrong'
request.flash['error'] = 'something wrong 2'
return HttpResponseRedirect("/")
and then in you template show it with
{% for message in flash.notice %}
{{ message }}
{% endfor }}
or
{% for message in flash.notice %}
{{ message }}
{% endfor }}
{% for message in flash.error %}
{{ message }}
{% endfor }}
- [Django]-Django: Use of DATE_FORMAT, DATETIME_FORMAT, TIME_FORMAT in settings.py?
- [Django]-Suppress "?next=blah" behavior in django's login_required decorator
- [Django]-Disable session creation in Django
5đź‘Ť
I liked the idea of using the message framework, but the example in the django documentation doesn’t work for me in the context of the question above.
What really annoys me, is the line in the django docs:
If you're using the context processor, your template should be rendered with a RequestContext. Otherwise, ensure messages is available to the template context.
which is incomprehensible to a newbie (like me) and needs to expanded upon, preferably with what those 2 options look like.
I was only able to find solutions that required rendering with RequestContext… which doesn’t answer the question above.
I believe I’ve created a solution for the 2nd option below:
Hopefully this will help someone else.
== urls.py ==
from django.conf.urls.defaults import *
from views import *
urlpatterns = patterns('',
(r'^$', main_page, { 'template_name': 'main_page.html', }, 'main_page'),
(r'^test/$', test ),
== viewtest.py ==
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
def test(request):
messages.success( request, 'Test successful' )
return HttpResponseRedirect( reverse('main_page') )
== viewmain.py ==
from django.contrib.messages import get_messages
from django.shortcuts import render_to_response
def main_page(request, template_name ):
# create dictionary of items to be passed to the template
c = { messages': get_messages( request ) }
# render page
return render_to_response( template_name, c, )
== main_page.html ==
{% block content %}
{% if messages %}
<div>
{% for message in messages %}
<h2 class="{{message.tag}}">{{ message.message }}</h2>
{% endfor %}
</div>
{% endif %}
{% endblock %}
- [Django]-Django AutoField with primary_key vs default pk
- [Django]-How do you configure Django to send mail through Postfix?
- [Django]-Passing variable urlname to url tag in django template
4đź‘Ť
I have read and checked all answers, and it seems to me that the way to go now is using the messaging framework. Some of the replies are fairly old and have probably been the right way at the time of the posting.
- [Django]-Filtering using viewsets in django rest framework
- [Django]-Django rest framework: query parameters in detail_route
- [Django]-Django gunicorn sock file not created by wsgi
3đź‘Ť
There is a lot of solutions
1 Use Django-trunk version – it support sending messages to Anonymous Users
2 Sessions
def view1(request):
request.session['message'] = 'Hello view2!'
return HttpResponseRedirect('/view2/')
def view2(request):
return HttpResponse(request.session['message'])
3 redirect with param
return HttpResponseRedirect('/view2/?message=Hello+view2')
4 Cookies
- [Django]-Django filter JSONField list of dicts
- [Django]-Constructing Django filter queries dynamically with args and kwargs
- [Django]-Django, Turbo Gears, Web2Py, which is better for what?
1đź‘Ť
Can you just pass the message as a query param oon the URL to which you’re redirecting? It’s not terribly RESTy, but it ought to work:
return HttpResponseRedirect('/polls/%s/results/?message=Updated" % p.id)
and have that view check for a message param, scrub it for nasties, and display it at the top.
- [Django]-Django-nonrel + Django-registration problem: unexpected keyword argument 'uidb36' when resetting password
- [Django]-How to delete project in django
- [Django]-Django: How to format a DateField's date representation?
1đź‘Ť
I think this code should work for you
request.user.message_set.create(message="This is some message")
return http.HttpResponseRedirect('/url')
- [Django]-How to get username from Django Rest Framework JWT token
- [Django]-Django Rest JWT login using username or email?
- [Django]-Django model constraint for related objects
0đź‘Ť
While all suggestions so far work, I would suggest going with Ry4an’s (pass it in the request URL) – just change the actual text to a coded text within a predefined set of text messages.
Two advantages here:
- Less chance of something hacking through your scrubbing of bad content
- You can localize your messages later if needed.
The other cookie related methods.. well, they don’t work if the browser doesn’t support cookies, and are slightly more expensive.. But only slightly. They’re indeed cleaner to the eye.
- [Django]-Django: Filter a Queryset made of unions not working
- [Django]-How to produce a 303 Http Response in Django?
- [Django]-Django middleware difference between process_request and process_view
0đź‘Ť
Take a look at Django’s messages framework. http://docs.djangoproject.com/en/dev/ref/contrib/messages/#ref-contrib-messages
- [Django]-How to get username from Django Rest Framework JWT token
- [Django]-How to get getting base_url in django template
- [Django]-Django – No module named _sqlite3
0đź‘Ť
You could also have the redirect url be the path to an already parameterized view.
urls.py:
(r'^some/path/(?P<field_name>\w+)/$', direct_to_template,
{'template': 'field_updated_message.html',
},
'url-name'
),
views.py:
HttpResponseRedirect( reverse('url-name', args=(myfieldname,)) )
Note that args= needs to take a tuple.
- [Django]-Why is logged_out.html not overriding in django registration?
- [Django]-Django connection to postgres by docker-compose
- [Django]-Handling race condition in model.save()
0đź‘Ť
The solution used by Pydev UA is the less intrusive and can be used without modifying almost nothing in your code. When you pass the message, you can update your context in the view that handles the message and in your template you can show it.
I used the same approach, but instead passing a simple text, passed a dict with the information in useful fields for me. Then in the view, updated context as well and then returned the rendered template with the updated context.
Simple, effective and very unobstrusive.
- [Django]-How to delete project in django
- [Django]-Django: How to check if the user left all fields blank (or to initial values)?
- [Django]-Check if celery beat is up and running