本文介绍了django模型形式继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的modelform中使用了Django modelform继承,但似乎不起作用,这是我的代码示例

I'm using django modelform inheritence in my modelform but it seems to be not working here is my code sample

class ArticleForm(forms.ModelForm):
  title = forms.CharField(required=True)
  sites = forms.ModelMultipleChoiceField(required=True, queryset= Sites.objects.all().order_by('name'), widget=forms.SelectMultiple())

class ArticleAddForm(ArticleForm):
   class Meta(ArticleForm.Meta):
       exclude = ('sites',)

我想从 ArticleAddForm中排除网站,但在验证时会引发表格验证错误,必填字段

i want to exclude "sites" from "ArticleAddForm" but while validating it is raising form validation error sites field required please help?

推荐答案

我相信ModelForms不能很好地处理继承。

ModelForms don't handle inheritance so well, I believe.

可能最好的方法是删除子类中的必需标志:

Probably the best ou can do is remove the required flag in the child class:

def __init__(self, *args, **kwargs):
    super(ArticleAddForm, self).__init__(*args, **kwargs)
    self.base_fields['sites'].required = False
    self.base_fields['sites'].widget = HiddenInput() # if you want

这篇关于django模型形式继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-09 21:37