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

时间:2019-06-02 04:38:24

标签: python django modelform

我有一个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中的小部件?

1 个答案:

答案 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)))