0

我的问题是 python/django 混合。我有一个将显示一些字段的表单模型。根据此模型的某些参数,发送到创建此对象的元类的数据应该不同。但是,在 Meta 的主体内,我怎样才能达到这个参数呢?我应该使用一些全局变量而不是对象参数(因为它只是为了临时存储值而引入的)?

class MyForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)   
        instance = kwargs.get("instance")
        self.type = None
        try:
            type = self.instance.template_id
        except:
            pass

    class Meta:
        model = ContentBase
        fields = ["title", "slug", "description", "text", "price",]

        #here I need to have the value of 'type'
        if type != 2:
            try:
                fields.remove("price")
            except:
                pass
4

2 回答 2

2

你不能在 Meta 中做任何动态的事情。那不是它的用途。

为什么你不能在里面做这一切__init__?您可以self.fields从那里进行修改。

于 2010-10-12T15:59:23.373 回答
1

正如丹尼尔提议的那样,我把整个事情搬到了__init__

    type = None
    try:
        type = self.instance.template_id
    except:
        pass

    if type != 2:
        self.fields.pop("price")
    else:
于 2010-10-12T18:08:24.840 回答