我试图让django中的消息框架起作用。
以下是我的settings.py
的有趣内容INSTALLED_APPS = (
'django.contrib.sessions',
'django.contrib.messages',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
)
我没有向TEMPLATE_CONTEXT_PROCESSORS
添加任何内容,因此它是默认值。
我的观点,我想要显示的消息:
from django.contrib.messages import get_messages
class ProfileFrontpage(TemplateView):
def get(self, request, *args, **kwargs):
if request.user.is_authenticated():
#Get messages
messages = get_messages(request)
#Get the user
user = self.request.user
#Used benefit
used_benefit_list = Benefit.published.filter(used_benefit__user = user)
return render(request, "accounts/frontpage.html", {"messages": messages, "used_benefit_list": used_benefit_list})
else:
return render(request, 'accounts/not_authenticated.html')
模板:
{% if messages %}
{% for message in messages %}
<div class="alert {{ message.tags }}">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
{{ message }}
</div>
{% endfor %}
{% endif %}
这是我的表单,应该在表单有效时创建一条消息:
def show_profileform(request):
if request.user.is_authenticated():
user = request.user
ProfileFormInlineFormSet = inlineformset_factory(User, Profile, form=ProfileForm, can_delete=False)
if request.method == "POST":
form = UserForm(request.POST, request.FILES, instance=request.user, prefix="main")
formset = ProfileFormInlineFormSet(request.POST, request.FILES, instance=request.user, prefix="nested")
if 'submit' in request.POST:
if form.is_valid() and formset.is_valid():
u = User.objects.get(username = request.user)
#Save to database
user = form.save()
profile = formset.save()
messages.success(request, "Settings updated", extra_tags='alert-success')
return HttpResponseRedirect('/accounts/')
else:
form = UserForm(instance=request.user, prefix="main")
formset = ProfileFormInlineFormSet(instance=request.user, prefix="nested")
return render(request, "accounts/form.html", {"form":form, "formset":formset})
else:
return render(request, 'accounts/not_authenticated.html')
任何人都知道为什么邮件不可见?
答案 0 :(得分:1)
TEMPLATE_CONTEXT_PROCESSORS
设置by default包含消息上下文处理程序。因此,您无需在视图中执行get_messages(request)
。实际上,在您的情况下它是有害的:对get_messages()
的调用获取消息并清除消息存储。然后,上下文处理器尝试执行相同操作,但找不到任何内容,因为您的视图已清除它们。然后,它会继续在模板上下文中设置messages
键,并覆盖视图中的值。
简而言之:从ProfileFrontpage
视图中删除处理消息,它应该可以正常工作。