Django 消息拒绝显示

Django messages refuse to display

我一直在尝试在用户 post 在我的网站上发表无效评论(例如空白 post)时显示警报。我决定使用消息框架,但它似乎不起作用。我已确保应用程序、中间件和模板上下文处理器是正确的,并且我的视图使用的是 RequestContext 对象。如果我在模板中使用 {% debug %},我可以看到 "messages" 变量集,但其中什么也没有。

settings.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'polls',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

TEMPLATE_CONTEXT_PROCESSORS =  ("django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.tz",
    "django.core.context_processors.request",
    "django.contrib.messages.context_processors.messages",
)

views.py

def detail(request, question_id):
    uid = request.session.get('uid', 0);
    q = get_object_or_404(Question, pk=question_id);

    context = RequestContext(request, {'question': q, 'uid':uid});
    return render(request, 'detail.html', context_instance=context);

def post_comment(request, question_id):
    try:
        if (request.POST['comment_text'] == ""):
            messages.error(request, "Cannot submit an empty comment!");
            return HttpResponseRedirect(reverse('detail', kwargs={'question_id': question_id}));
        else:
            comment = Comment(
                question = Question.objects.get(id=question_id),
                submitter = request.session['uid'],
                text = sanitizer.clean(request.POST['comment_text'])
                );

            comment.save();

    except Exception, e:
        raise e;
    else:
        return HttpResponseRedirect(reverse('detail', kwargs={'question_id': question_id}));

detail.html

{% extends "base.html" %}

{% block content %}
{% if messages %}
<ul class="messages">
    {% for m in messages %}
    <li{% if m.tags %} class="{{ m.tags }}"{% endif %}>{{ m }}</li>
    {% endfor %}
</ul>
{% endif %}
{%endblock%}

默认情况下,messages 将使用 storage.fallback.FallbackStorage 存储后端,即 "first uses CookieStorage, and falls back to using SessionStorage for the messages that could not fit in a single cookie"。如此有效,它使用 cookie 作为存储后端。如果您的网站有任何可能影响它的内容,您可以尝试将其设置为专门使用会话:

 MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'