如何为模型创建基于类的创建视图?

如何为模型创建基于类的创建视图?

问题描述:

我想要做的是功能视图的Django样板。这里的任何帮助都非常值得赞赏,因为这些文档显示了模板视图和列表视图的示例,但对于基于模型的通用视图,我发现很少。我错过了文档中的示例吗?如何为模型创建基于类的创建视图?

我有一个模型,表示日历中的一个条目。有一个外键用于拥有该条目的另一个对象(不是用户)。我想要做的只是创建条目,确保条目的外键已正确设置,然后将用户返回到相应的日历页面。

虽然我不知道基于类的泛型视图如何接收它们的URL参数,但我不清楚如何设置success_url,以便它重用最初传递到创建URL的id。再次感谢您的帮助。

我在问什么,本质上来说,就是,什么是下面的基于类的通用视图相当于:

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通用视图,在dispatch()设置类/课程方法,并通过覆盖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()) 

如果你不定制CourseEntryFormModelForm,那么你就可以离开了form_class财产。

不幸的是,不可能在form_valid()方法中调用super()--由于写入的方式将意味着对象将被再次保存。

如果你需要的类(?当然)实例在模板下,然后就可以在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 
+2

您可以直接使用'form.instance'设置'course',而不是手动将对象保存在'form_valid()'中。这使得它也可以再次调用'super()'。 – stschindler 2013-08-16 12:20:54

的替代马特·奥斯汀的答案可能是覆盖get_form方法:

from django.shortcuts import get_object_or_404 
from django.views.generic import CreateView 

class CourseEntryCreateView(CreateView): 
    form_class = CourseEntryForm 
    model = CourseEntry 

    def get_form(self, form_class): 
     form = super(CustomCreateView, self).get_form(form_class) 
     course = get_object_or_404(Class, pk=self.kwargs['class_id']) 
     form.instance.course = course 
     return form 

这样,.course是在上下文中CourseEntry实例,并在当表单POST时保存创建的实例。