获取此对象的元类中对象的参数

2024-03-28 08:41:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题是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

Tags: 对象instance模型self参数inittypeargs
2条回答

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

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

    if type != 2:
        self.fields.pop("price")
    else:

你不能在Meta中做任何动态的事情。不是为了这个。在

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

相关问题 更多 >