我有一个ModelForm
,其中有一个额外的字段,它是自定义窗口小部件。我可以为窗口小部件添加一个额外的字段,并在构造窗口小部件时将任意键值传递给它。我还可以在ModelForm
函数的__init__
中访问模型数据。
我的问题在于,在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.
我也尝试在self.some_data
中设置__init__
,但是当我在课堂结束时设置self.some_data
时尝试使用some_extra_field
时,仍然无法访问。
如何将模型数据传递到ModelForm
中的小部件?
答案 0 :(得分:0)
如果我正确地遵循了您的需求,则只需在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 = ...
中编辑或重新分配窗口小部件即可完成此操作。像这样:
def user_grade(statistic=None):
grades = []
for _ in range(5):
grades.append(float(input("Enter Grade (percentage): ")))
if statistic == "max":
print('Max: {}'.format(max(grades)))
elif statistic == "min":
print('Min: {}'.format(min(grades)))
else:
print('Average: {}'.format(sum(grades) / len(grades)))