【发布时间】: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 中的小部件?
【问题讨论】: