开发服务器使用 django1.3,但部署服务器由 django1.4 提供支持。消息框架在 django1.4 上根本不起作用,但在 1.3 上用以下代码工作得很好。
设置.py
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
... ,
)
视图.py
from django.contrib import messages
from django.http import HttpResponseRedirect
...
def some_view(request):
...
mess1 = 'Thank you! Your message was received.'
messages.info(request, mess1)
return HttpResponseRedirect('/contact/')
模板
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
{{ message }}
</li>
{% endfor %}
</ul>
{% endif %}