2014-05-20 140 views
0

我想從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形式被處理,但usercreator似乎並沒有得到來自GenericCreate類設置...我收到以下錯誤:

NOT NULL constraint failed: articles_article.usercreator_id 

當我在OrganizationCreate.form_valid()中強制form.instance.usercreator = self.request.user時,我不會收到此錯誤。

這就好像繼承不起作用。如何避免在OrganizationCreate.form_valid()中顯式設置createuser並使用GenericCreate.form_valid()?

回答

0

您打電話給super的班級不對。在OrganizationCreate中,您必須致電super(OrganizationCreate, self)super的第一個參數應該與您調用它的類相同。您的調用的效果是GenerticCreate在繼承層次結構中被跳過,所以它的方法不會被調用。