1

我也可以创建不同类型的表单,但这很乏味。那么是否可以将类型传递给表单,然后相应地显示表单?这段代码显示NameError: name 'review_type' is not defined

class Contest1_for_review(ModelForm, review_type):

    class Meta:

        model = Contest1

        decision = review_type + '_decision'
        comment = review_type +'comment'

        fields = [
            decision,
            comment,
        ]

是否可以像这样将参数传递给元类?

4

1 回答 1

1

表单是一个类,当它在 HTML 中呈现时,它呈现表单类的一个实例。因此,当将值传递给该实例时,您可以使用它的__init__方法。例如:

class Contest1_for_review(ModelForm):

    def __init__(self, *args, **kwargs):
        review_type = kwargs.pop('review_type')  # <-- getting the value from keyword arguments
        super().__init__(*args, **kwargs)
        self.fields[f'{review_type}_decision'] = forms.CharField()
        self.fields[f'{review_type}_comment'] = forms.CharField()

    class Meta:
        model = Contest1
        fields = "__all__"

此外,您需要将review_type视图的值发送到表单。像这样在基于函数的视图中:

form = Contest1_for_review(review_type="my_value")

或用于get_form_kwargs从基于类的视图发送值。仅供参考:您不需要更改Meta类中的任何内容。


更新:

从评论中的讨论来看,OP 应该使用forms.Form而不是ModelForm因为使用模型表单需要Meta类中的字段/排除值。

于 2019-11-25T06:26:08.507 回答