2011-01-26 63 views

回答

4

據我所知,使用傳統通用視圖並不是一種簡單的方法。我一直覺得通用視圖的文檔非常缺乏,所以從來沒有使用它們。

從理論上講,您可以通過假設重定向意味着成功提交來使用裝飾器。

所以,你可以寫這樣的事情(沒有這個代碼已經過測試):

urls.py

try: 
    from functools import wraps 
except ImportError: 
    from django.utils.functional import wraps 
from django.http import HttpRedirectResponse 
from django.contrib import messages 
from django.views.generic import * 

def add_message(success_message=None): 
    def decorator(func): 
     def inner(request, *args, **kwargs): 
      resp = func(request, *args, **kwargs) 
      if isinstance(resp, HttpRedirectResponse): 
       messages.success(request, message) 
      return resp 
     return wraps(func)(inner) 
    return decorator 



student_info_edit = { 
    'template_name': 'myapp/student/form.html', 
    'template_object_name': 'student', 
    'form_class': studentForm, 
} 

student_info_new = { 
    'template_name': 'myapp/student/form.html', 
    'form_class': studentForm, 
    'post_save_redirect': '/myapp/students/', 
} 

urlpatterns += patterns('', 
    url(r'^students/$', list_detail.object_list, { 'queryset': Student.objects.all() }, name="students"), 
    url(r'^students/(?P<object_id>\d+)/$', add_message("Student record updated successfully")(create_update.update_object), student_info_edit, name="student_detail"), 
    url(r'^students/new$', add_message("The student was added successfully.")(create_update.create_object), student_info_new, name="student_new"), 
) 

所有這一切說和編碼,則Django 1.3中引入class-based generic views,所以如果你有興趣轉向Django 1.3,你應該看看那些。他們可能會允許更多的定製,不確定。

從長遠來看,我很少看到使用通用視圖的好處形式,而這對於諸如添加/更新之類的東西來說是雙倍的。

+0

謝謝,我已經決定不使用通用視圖,因爲它不夠靈活地處理實際場景。 – Myth 2011-01-26 09:38:39

+0

我接受這個答案,因爲它幫助我做出了很多決定(對於其他人:我還沒有測試代碼) – Myth 2011-01-26 09:45:44

35

Django 1.6+,使用任何class-based generic views,你可以依靠successMessageMixin。就像將mixin添加到類定義並將success_message屬性設置爲任何您想要的一樣簡單。

正如Olivier Verdier所提到的,請記住在您的主模板中輸入display messages

docs一個簡單的例子:

from django.contrib.messages.views import SuccessMessageMixin 
from django.views.generic.edit import CreateView 
from myapp.models import Author 

class AuthorCreate(SuccessMessageMixin, CreateView): 
    model = Author 
    success_url = '/success/' 
    success_message = "%(name)s was created successfully" 

更復雜的例子:

from django.contrib.messages.views import SuccessMessageMixin 
from django.views.generic.edit import CreateView 
from myapp.models import ComplicatedModel 

class ComplicatedCreate(SuccessMessageMixin, CreateView): 
    model = ComplicatedModel 
    success_url = '/success/' 
    success_message = "%(calculated_field)s was created successfully" 

    def get_success_message(self, cleaned_data): 
     # cleaned_data is the cleaned data from the form which is used for string formatting 
     return self.success_message % dict(cleaned_data, 
              calculated_field=self.object.calculated_field)