【问题标题】:Django pass model to widget in ModelFormDjango将模型传递给ModelForm中的小部件
【发布时间】:2019-06-02 04:38:23
【问题描述】:

我有一个ModelForm,它有一个额外的字段,它是一个自定义小部件。我可以添加一个带有小部件的额外字段,并在构建小部件时将任意键值传递给它。我还可以在__init__ 函数中访问ModelForm 中的模型数据。

我的问题在于,在ModelForm 中添加一个额外的字段需要在__init__ 函数之外进行,而只能从__init__ 函数中访问模型数据。

class SomeForm(forms.ModelForm):
        title = None
        def __init__(self, *args, **kwargs):
                some_data = kwargs['instance'].some_data
                # ^ Here I can access model data.
                super(SomeForm, self).__init__(*args, **kwargs)
                self.fields['some_extra_field'] = forms.CharField(widget= SomWidget())
                # ^ This is where I would pass model data, but this does not add the field.
        class Meta:
                model = Page 
                fields = "__all__"
        some_extra_field = forms.CharField(widget= SomeWidget())
        # ^ I can add a field here, but there's no way to pass some_data to it.

我也尝试在__init__ 中设置self.some_data,但是当我在课程结束时设置some_extra_field 时尝试使用self.some_data 时仍然无法访问。

应该如何将模型数据传递给ModelForm 中的小部件?

【问题讨论】:

    标签: python django modelform


    【解决方案1】:

    如果我正确地遵循了您的需求,您只需在__init__ 中编辑或重新分配小部件即可。比如:

    class SomeForm(forms.ModelForm):
        title = None
        def __init__(self, *args, **kwargs):
            some_data = kwargs['instance'].some_data
            super(SomeForm, self).__init__(*args, **kwargs)
            # Pass whatever data you want to the widget constructor here
            self.fields['some_extra_field'].widget = SomWidget(foo=...))
            # or possibly (depending on what you're doing)
            self.fields['some_extra_field'].widget.foo = ...
    

    【讨论】:

    • 首先,谢谢。由于some_extra_field 不在模型中,因此尝试将.widget 分配给数组会导致键错误。这可能是版本控制吗?
    • 好吧,您仍然需要声明该字段 - 如果唯一不寻常的是您想根据 __init__ 的参数调整小部件,请像在您的示例(在__init__ 之外)应该足够了。如果您总是计划重新分配小部件,那么您在声明中使用什么小部件并不重要 - 将其保留为默认值应该没问题。如果您可能没有模型实例(例如在创建视图中),您应该使用您想要的任何小部件。
    • __init__ 方法中创建一个新字段并将其插入self.fields 也是正常的,但如果您只想调整小部件,则没有必要。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-02
    • 1970-01-01
    • 2012-04-10
    • 2021-02-03
    • 1970-01-01
    • 2016-11-17
    相关资源
    最近更新 更多