Django 将模型传递给 ModelForm 中的小部件

Django pass model to widget in ModelForm

我有一个 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,但是当我尝试使用self.some_data时仍然无法访问,当我在some_extra_field时设置some_extra_field class.

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

如果我按照您的需要正确执行,您只需在 __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 = ...