gpt4 book ai didi

python - Django 消息拒绝显示

转载 作者:行者123 更新时间:2023-11-30 23:13:43 26 4
gpt4 key购买 nike

我一直在尝试在用户在我的网站上发布无效评论(例如空白帖子)时显示警报。我决定使用消息框架,但它似乎不起作用。我已确保应用程序、中间件和模板上下文处理器正确,并且我的 View 使用 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 存储后端,该后端“首先使用 CookieStorage,然后回退到使用 SessionStorage 来存储无法发送的消息”适合单个 cookies ”。如此有效,它使用 cookie 作为存储后端。如果您的网站有任何可能影响该问题的内容,您可以尝试将其设置为专门使用 session :

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

关于python - Django 消息拒绝显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29176658/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com