【问题标题】:How to add non model field to ModelForm in Django?如何在 Django 中向 ModelForm 添加非模型字段?
【发布时间】: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.??????????

【问题讨论】:

    标签: django django-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 参数。例如:stackoverflow.com/a/3420588/630877
    猜你喜欢
    • 2012-01-26
    • 2011-08-08
    • 2011-06-07
    • 2015-09-06
    • 2021-10-10
    • 2010-12-25
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多