gpt4 book ai didi

Django 1.7.4 : messages not showing up in TemplateView

转载 作者:行者123 更新时间:2023-12-01 15:29:24 29 4
gpt4 key购买 nike

我正在尝试将消息添加到第一个 View 并通过重定向将它们传递到第二个 View :

第一 View :

def index(request):
...etc...
messages.info(request, "My message!")
return redirect('second_view', pk=pk)

第二种观点:

class SecondView(TemplateView):                                                       

template_name = "template.html"

def get_context_data(self, **kwargs):
context = super(SecondView, self).get_context_data(**kwargs)
pk = kwargs.get('pk')
context.update({
'pk': pk,
})
return context

@method_decorator(login_required)
@method_decorator(ensure_csrf_cookie)
def dispatch(self, *args, **kwargs):
return super(SecondView, self).dispatch(*args, **kwargs)

template.html :

{% if messages %}                                                                                                        
<div>
<p>This is a test.</p>
{% for message in messages %}
{{message}}
{% endfor %}
</div>
{% endif %}

设置.py:

TEMPLATE_CONTEXT_PROCESSORS = (                                                     
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.request',
'accounts.context_processors.extra_context',
'django.contrib.messages.context_processors.messages',
)

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

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

但在我的 template.html 中,{% if messages %}返回假。我怎样才能让这些消息显示出来?

编辑:

如果我只是尝试将 {{messages}}在我的模板中,它呈现如下:<django.contrib.messages.storage.fallback.FallbackStorage object at 0x108271950>

但是当我调用{% if messages %}这不会返回 {%if%} 的内容声明。

编辑2:

我有一个测试,消息在 html 中正确显示,通过了:

  def test_home_page_signup_messages(self):                                       
data = create_signup_post_data()
url = reverse('signup')
response = self.client.post(url, data, follow=True)
messages = [m.message for m in list(response.context['messages'])]
self.assertIn("My message!", messages) # PASSES
self.assertIn("My message!", response.content) # PASSES

最佳答案

我认为这里的问题是重定向没有传递任何包含消息的上下文。 documentation explains that :

If you’re using the context processor, your template should berendered with a RequestContext. Otherwise, ensure messages isavailable to the template context.

因此,messages重定向后将不可用。但是,您可以使用 django.contrib.messages.get_messages 自行检索消息:

from django.contrib.messages import get_messages

class SecondView(TemplateView):
template_name = "template.html"

def get_context_data(self, **kwargs):
context = super(SecondView, self).get_context_data(**kwargs)
pk = kwargs.get('pk')
context.update({
'pk': pk,
'messages': get_messages(self.request),
})
return context

@method_decorator(login_required)
@method_decorator(ensure_csrf_cookie)
def dispatch(self, *args, **kwargs):
return super(SecondView, self).dispatch(*args, **kwargs)

回应:

EDIT:

If I simply try to put {{messages}} into my template, it renders like this: <django.contrib.messages.storage.fallback.FallbackStorage object at 0x108271950>

but when I call {% if messages %} this does not return the contents of the {%if%} statement.

这是我的确切代码,减去 URL:

# ------- URLS
# Django
from django.conf.urls import patterns, url

from .views import SecondView

urlpatterns = patterns("myapp.views",
url(r'^test/$', 'index'),
url(r'^test/(?P<pk>\d+)/$', view=SecondView.as_view(), name='second_view')
)

# ------- VIEWS

from django.views.generic import TemplateView
def index(request):
from django.contrib import messages
from django.shortcuts import redirect
messages.info(request, "My message!")
pk = 2
return redirect('second_view', pk=pk)

from django.contrib.messages import get_messages
from django.views.decorators.csrf import ensure_csrf_cookie
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
class SecondView(TemplateView):
template_name = "template.html"

def get_context_data(self, **kwargs):
context = super(SecondView, self).get_context_data(**kwargs)
pk = kwargs.get('pk')
context.update({
'pk': pk,
'messages': get_messages(self.request),
})
return context

@method_decorator(login_required)
@method_decorator(ensure_csrf_cookie)
def dispatch(self, *args, **kwargs):
return super(SecondView, self).dispatch(*args, **kwargs)

# ------- TEMPLATE
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
{% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %}
{{ message }}
</li>
{% endfor %}
</ul>
{% endif %}
</body>
</html>

关于 Django 1.7.4 : messages not showing up in TemplateView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28704559/

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