模型表子类和隐藏元素

时间:2011-05-25 19:11:30

标签: django django-models django-forms

根据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"]

但是因为它是在父语句中声明的,所以无论如何它都会被渲染。我也尝试将其声明为headline =“”但结果相同。

解决方案:

def __init__(self, *args, **kwargs):
    super(NameOfSubclassedForm, self).__init__(*args, **kwargs)
    del self.fields['headline'] # field that needs removing

TIA

*更新:在我的原始帖子中,我偶然排除了外部元

* update2:已报告错误:https://code.djangoproject.com/ticket/13971

* update3:添加解决方案

1 个答案:

答案 0 :(得分:0)

我相信你只是把你的排除放在了错误的地方。试试这样:

class ArticleForm(ModelForm):
    class Meta:
        model = Article
        exclude = ("headline",)

查看the docs

相关问题