模型窗体的子类化和隐藏元素

问题描述

| 根据Django文档,我可以执行以下操作:
class Article(models.Model):
    headline = models.CharField(max_length=200,null=True,blank=True,help_text=\"Use puns liberally\")
    content = models.TextField()


class ArticleForm(ModelForm):
    headline = MyFormField(max_length=200,required=False,help_text=\"Use puns liberally\")

    class Meta:
        model = Article
就我而言,我希望\“标题\”根本不作为子类中的选项显示。最好的方法是什么?我已经尝试过“排除”
class ArticleForm(ModelForm):


    class Meta:
        model = Article
        exclude = [\"headline\"]
但是由于它是在父级中声明的,所以无论如何都会渲染它。我也尝试将其声明为标题= \“ \”,但结果相同。 解:
def __init__(self,*args,**kwargs):
    super(NameOfSubclassedForm,self).__init__(*args,**kwargs)
    del self.fields[\'headline\'] # field that needs removing
TIA *更新:在我的原始帖子中,我意外地排除了外部Meta * update2:已报告的错误:https://code.djangoproject.com/ticket/13971 * update3:添加解决方案     

解决方法

我相信您只是将排除对象放在错误的位置。像这样尝试:
class ArticleForm(ModelForm):
    class Meta:
        model = Article
        exclude = (\"headline\",)
查看文档。