模型表单子类化和隐藏元素
根据 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信您只是将排除项放在了错误的位置。尝试这样:
查看 文档。
I believe you simply have put your exclude in the wrong place. Try it like this:
Check out the docs.