我最近升级到了Django 1.3,我想开始使用Messages系统。
我已将我的中间件,模板上下文处理器以及消息添加到INSTALLED_APPS
MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',
'facebook.djangofb.FacebookMiddleware',
'annoying.middlewares.RedirectMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
"django.contrib.messages.context_processors.messages",
)
INSTALLED_APPS = (
'django.contrib.messages',
)
我只是根据一个简单计算的视图进行测试。
在管理员中,消息显示,但是当我尝试在base.html文件中呈现它们时,我收到以下错误。
Caught TypeError while rendering: 'module' object is not iterable
并且在堆栈中它在这里失败。
{% for message in messages %}
我也删除了for语句,我仍然收到以下错误,仅此而已
<module 'django.contrib.messages' from '/Users/ApPeL/.virtualenvs/mysite.com/lib/python2.7/site-packages/django/contrib/messages/__init__.py'>
有什么想法吗?
答案 0 :(得分:2)
我刚遇到这个问题。我在上下文处理器中包含了以下内容:
from django.contrib import messages
...
def allrequests(request):
ctx = {
...
'messages': messages
}
return ctx
确保您没有在上下文中设置messages
,因为django.contrib.messages.context_processors.messages
以正确的方式设置了{{1}}。
答案 1 :(得分:-1)
你是如何在settings.py中使用MIDDLEWWARE_CLASSES和TEMPLATE_CONTEXT_PROCESSORS的,它必须如下所示:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.i18n",
"django.core.context_processors.request",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages"
)
在INSTALLED_APPS中:
'django.contrib.messages'
在你的模板中(你忘了if?):
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
我希望它会对你有所帮助。