我在我的模型中使用django modelform inheritence,但似乎这里没有工作是我的代码示例
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”中排除“网站”,但在验证时是否需要提高表单验证错误网站字段,请帮忙吗?
答案 0 :(得分:2)
我相信,ModelForms不能很好地处理继承。
可能最好的办法就是删除子类中的required
标志:
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
答案 1 :(得分:0)
在您的视图中,您需要使用Article对象初始化ArticleAddForm以填充空白字段,即排除的字段。例如:
sites = Sites.objects.all() # modify this according to your needs
article = Article(title='', sites=sites)
form = ArticleAddForm(request.POST, instance=article)
form.save()