<p>据我所知,没有一种简单的方法可以使用传统的泛型视图来实现这一点。我一直觉得关于泛型视图的文档非常缺乏,因此从未使用过它们。</p>
<p>理论上,可以通过假设重定向意味着成功提交来使用decorator。</p>
<p>所以你可以写这样的东西(这些代码都没有经过测试):</p>
<p><strong>url.py</strong>:</p>
<pre><code>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"),
)
</code></pre>
<p>尽管如此,Django 1.3引入了<a href="http://docs.djangoproject.com/en/dev/topics/class-based-views/" rel="nofollow"><em>class-based</em> generic views</a>,因此如果您对进入django1.3感兴趣,您应该研究一下这些。他们可能允许更多的定制,不确定。</p>
<p>从长远来看,我很少看到使用泛型视图的优点表单,而对于像add/update这样的东西,这一点就加倍了。</p>