模型表单子类化和隐藏元素

发布于 2024-11-09 17:19:12 字数 1108 浏览 0 评论 0原文

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

*更新:在我原来的帖子中,我意外地排除了外部元

*更新2:已报告错误:https://code.djangoproject.com/ticket/13971

*update3:添加解决方案

Accordingly to the Django docs I can do the following:

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

In my case I would like "headline" not to be displayed at all as an option in a subclass. What is the best method to do that? I already tried "exclude"

class ArticleForm(ModelForm):


    class Meta:
        model = Article
        exclude = ["headline"]

But since it is declared in the parent it is rendered anyways. Also I tried declaring it as headline = "" but same result.

Solution:

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

TIA

*update: in my original post I placed exclude outside meta by accident

*update2: bug already reported: https://code.djangoproject.com/ticket/13971

*update3: Added Solution

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

偏爱自由 2024-11-16 17:19:12

我相信您只是将排除项放在了错误的位置。尝试这样:

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

查看 文档

I believe you simply have put your exclude in the wrong place. Try it like this:

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

Check out the docs.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文