继承似乎不起作用

时间:2014-05-20 03:09:05

标签: python django

我试图从django CBV中的form_valid()中取出公共代码。代码如下:

class GenericCreate(CreateView):
    def form_valid(self, form):
        form.instance.usercreator = self.request.user
        form.instance.slug = unique_slug(form.instance.headline, Article)
        return super(GenericCreate, self).form_valid(form)

class ArticleCreate(GenericCreate):
    success_url = '/'
    form_class = ArticleForm
    template_name  = "articles/article_form.html"


class OrganizationCreate(GenericCreate):
    success_url = '/'
    form_class = OrganizationForm
    template_name  = "organizations/organization_form.html"

    def form_valid(self, form):
        form.instance.pub_date = timezone.now()
        #        form.instance.usercreator = self.request.user # no error if this is uncommented
        return super(GenericCreate, self).form_valid(form)

提交OrganizationForm时,处理了OrganizationCreate表单,但是似乎没有从GenericCreate类设置usercreator ...我收到以下错误:

 NOT NULL constraint failed: articles_article.usercreator_id

当我在OrganizationCreate.form_valid()中强制form.instance.usercreator = self.request.user时,我没有收到此错误。

好像继承不起作用。我怎样才能不必在OrganizationCreate.form_valid()中显式设置createuser并使用GenericCreate.form_valid()?

1 个答案:

答案 0 :(得分:0)

您正在使用错误的类调用super。在OrganizationCreate,您必须致电super(OrganizationCreate, self)super的第一个参数应该与您调用它的类相同。调用的效果是在继承层次结构中跳过GenerticCreate,因此不会调用其方法。