我正在尝试做的是功能 View 的 Django 样板。非常感谢这里的任何帮助,因为文档显示了模板 View 和 ListView 的示例,但我发现基于模型的通用 View 很少。我错过了文档中的示例吗?
我有一个代表日历中的条目的模型。拥有该条目的另一个对象(不是用户)有一个外键。我想做的只是创建条目,确保正确设置条目的外键,然后将用户返回到相应的日历页面。
但是,我不知道基于类的通用 View 如何接收它们的 URL 参数,并且我不清楚如何设置 success_url 以便它重用最初传递给创建 URL 的 id。再次,提前感谢您的帮助。
本质上,我要问的是,什么是基于类的通用 View ,相当于以下内容:
def create_course_entry(request, class_id):
'''Creates a general calendar entry.'''
if request.method == 'POST':
form = CourseEntryForm(request.POST)
if form.is_valid():
new_entry = form.save(commit=False)
new_entry.course = Class.objects.get(pk=class_id)
new_entry.full_clean()
new_entry.save()
return HttpResponseRedirect('/class/%s/calendar/' % class_id)
else:
form = CourseEntryForm()
return render_to_response('classes/course_entry_create.html',
{ 'class_id': class_id, 'form': form, },
context_instance=RequestContext(request))
最佳答案
您可以将 edit.CreateView
子类化通用 View ,在 dispatch()
中设置类(class)/类(class)方法,并通过覆盖 form_valid()
来保存它方法:
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.views.generic.edit import CreateView
class CourseEntryCreateView(CreateView):
form_class = CourseEntryForm
model = CourseEntry
def dispatch(self, *args, **kwargs):
self.course = get_object_or_404(Class, pk=kwargs['class_id'])
return super(CourseEntryCreateView, self).dispatch(*args, **kwargs)
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.course = self.course
self.object.save()
return HttpResponseRedirect(self.get_success_url())
如果您不自定义
CourseEntryForm
ModelForm
,那么您可以省略 form_class
属性(property)。很遗憾,无法调用
super()
在 form_valid()
方法 - 由于它的编写方式,意味着对象将被再次保存。如果您需要模板上下文中的 Class(类(class)?)实例,那么您可以在
get_context_data()
中添加它。方法: def get_context_data(self, *args, **kwargs):
context_data = super(CourseEntryCreateView, self).get_context_data(
*args, **kwargs)
context_data.update({'course': self.course})
return context_data
关于django - 如何为模型创建基于通用类的创建 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5607205/