django model form inheritance

时光总嘲笑我的痴心妄想 提交于 2019-12-25 05:18:29

问题


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',)

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


回答1:


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



回答2:


In your view, you need to initialize the ArticleAddForm with an Article object to fill the blank fields, i.e. the excluded fields. For example:

sites = Sites.objects.all()    # modify this according to your needs
article = Article(title='', sites=sites)
form = ArticleAddForm(request.POST, instance=article)
form.save()


来源:https://stackoverflow.com/questions/12645875/django-model-form-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!