Django 1.7.4:消息未显示在TemplateView中

时间:2015-02-24 19:29:11

标签: django

我尝试将消息添加到第一个视图并将其传递给第二个带有重定向的视图:

第一个观点:

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 %}  

settings.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%}语句的内容。

EDIT2:

我有一个测试,其中消息在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

2 个答案:

答案 0 :(得分:2)

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

  

如果您正在使用上下文处理器,那么您的模板应该是   使用RequestContext呈现。否则,请确保消息   可用于模板上下文。

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

回应:

  

编辑:

     

如果我只是尝试将{{messages}}放入我的模板中,它会像这样渲染:<django.contrib.messages.storage.fallback.FallbackStorage object at 0x108271950>

     

但是当我调用{% if messages %}时,这不会返回{%if%}语句的内容。

这是我的确切代码,而不是网址:

# ------- 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>

答案 1 :(得分:0)

你有正确的进口吗?你使用哪个django版本?这适用于v1.7.4:

from django.contrib import messages
messages.add_message(request, messages.SUCCESS,"My message!")

下载我的项目以查看您需要的中间件的顺序: https://www.dropbox.com/s/qo601h7xjlk0ztu/project_for_messages.tgz?dl=0

从这里https://github.com/jpadilla/django-project-template

创建