Django消息拒绝显示

时间:2015-03-20 22:19:19

标签: python django messages

我一直在尝试在用户在我的网站上发布无效评论时显示提醒(例如空白帖子)。我决定使用消息框架,但它似乎不起作用。我确保应用程序,中间件和模板上下文处理器是正确的,并且我的视图使用的是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%}

1 个答案:

答案 0 :(得分:3)

默认情况下,messages将使用storage.fallback.FallbackStorage存储后端,后端“首先使用CookieStorage,然后使用SessionStorage回复无法放入单个Cookie的邮件”。如此有效,它使用cookie作为存储后端。如果您的网站上有任何可能影响该网站的内容,您可以尝试将其设置为专门使用会话:

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