2014-07-23 79 views
3

我希望在保存一行時使用帶有基於類的視圖的Django消息框架來顯示成功的消息,其代碼如下所示,但不顯示消息。使用基於類的視圖顯示成功的消息

任何幫助將是非常讚賞

#views.py 

from django.views.generic import ListView, CreateView, UpdateView, TemplateView 
from django.contrib.messages.views import SuccessMessageMixin 

class CreateEmployee(SuccessMessageMixin, CreateView): 
    model = Employee 
    template_name = 'employees/create.html' 
    form_class = frmCreate 

    def get_success_url(self): 
     return reverse('Employees:Create') 

    def get_context_data(self, **kwargs): 
     contexto = super(CreateEmployee, self).get_context_data(**kwargs) 
     contexto['action'] = reverse('Employees:Create') 
     return contexto 

    success_message = 'Employee successful created' 



#template 
#create.html 

<form action="{{ action }}" method="POST" role="form"> 
    {% csrf_token %} 

    {{ form.as_p }} 

    <input type="submit" value="Save" class="btn btn-success"> 
<form> 

{% if messages %} 
    <div class="col-lg-3 color03"> 
     <ul class="messages"> 
      {% for message in messages %} 
       <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> 
      {% endfor %} 
     </ul> 
    </div> 
{% endif %} 
+3

您是否嘗試將類CreateEmployee(CreateView,SuccessMessageMixin)中的參數更改爲類CreateEmployee(SuccessMessageMixin,CreateView),如django文檔中的示例所示:https://docs.djangoproject.com/en/dev/ref/contrib/messages /#添加消息在類基於視圖? – szymanskilukasz

+0

@szymanskilukasz我'做了建議的改變,這解決了我的問題,f..ck我,我很盲目 –

+1

@ElioClímacoHerrera我猜你的表單拋出錯誤而不是保存。你有檢查嗎? Mixin也應該按照文檔中所述的順序。 – sagarchalise

回答

0

你必須設置在settings.py

MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage' 

問候

1

消息存儲只需使用self.request這樣的:

from django.contrib import messages 
messages.add_message(self.request, messages.INFO, 'Hello world.') 
+0

我不能使它與接受的答案一起工作,我使用的是Django 1.11,這個工作正常。 'def form_valid(self,form)' – elsadek