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()?