我正在尝试将消息添加到第一个 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 %} 返回 false。我怎样才能让这些消息显示出来?

编辑:

如果我只是尝试将 {{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 :

因此,重定向后 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)
回应:

这是我的确切代码,减去 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/

10-15 19:55