如何在 Django 中向 ModelForm 添加非模型字段?

Posted

技术标签:

【中文标题】如何在 Django 中向 ModelForm 添加非模型字段?【英文标题】:How to add non model field to ModelForm in Django? 【发布时间】:2013-05-14 05:48:37 【问题描述】:

我希望这是有道理的,这就是我想做的事情(无论出于何种原因)

我想在我的模型表单中创建一个非模型表单字段

例如,下面我有一个模型表单,我想在 init 添加一个额外字段,该字段不包含在模型中称为模板。我不保存这个新字段,因此它不需要在我的模型中或我希望它存在(我用它做了一些花哨的 ajax 东西。)。

forms.py

class testForm(forms.ModelForm):
    def __init__(self, user=None, *args, **kwargs):
        super(testForm, self).__init__(*args, **kwargs)
        if user is not None:
            this_templates = Template.objects.for_user(user)

         self.fields["templates"] = forms.??????????

【问题讨论】:

【参考方案1】:

你快到了:

self.fields["templates"] = forms.CharField()

或者,如果您更喜欢其他字段类型,请检查 the documentation 以获取可能的选项。

如需更多背景信息,请查看Overloading Django Form Fields。

【讨论】:

好吧,像这样很酷…… self.fields["templates"] = forms.ChoiceField(queryset=this_templates) 但是这会产生错误:__init__() got an unexpected keyword argument '查询集' ChoiceField 不是ModelChoiceField。它不需要queryset,而是choices 参数。例如:***.com/a/3420588/630877

以上是关于如何在 Django 中向 ModelForm 添加非模型字段?的主要内容,如果未能解决你的问题,请参考以下文章

Django 1.4 - 在元字段 Model=User 的表单中向用户字段添加自定义错误消息

MySQL:如何在查询中向日期时间字段添加一天

如何在 Django 的 ModelForm 中使用请求

在Android应用程序中向GridView添加一组按钮

如何在 Modelform 的网格中呈现 Django CheckoxInput?

如何在 Django ModelForm 中获取实例