1
我試圖讓django中的消息框架工作。Django 1.6 - 消息沒有顯示
這裏是我還沒有添加任何東西TEMPLATE_CONTEXT_PROCESSORS
我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',
)
有趣的位,所以它是默認值。
我的看法,我想要的消息顯示:
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')
任何人都知道爲什麼消息不可見?
當消息沒有顯示時,我將'get_messages()'添加到了我的視圖中。刪除我的'ProfileFrontpage'視圖中的代碼並重新啓動我的服務器,沒有任何區別。該消息不顯示。 –
絕對保留'get_message'去除。模板的其餘部分是怎樣的?是基本模板中的消息輸出?如果不是,它是在一個塊內? – sk1p
我有一個子模板中的塊內的消息,但將其移出到base.html模板,而不是在塊內。仍然沒有消息。 –