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

发布于 2024-09-27 03:21:56 字数 733 浏览 1 评论 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

My problem is a python/django mix. I have a form model that will display some fields. Basing on some parameter of this model, the data sent to metaclass creating this object should differ. But how can I reach this parameter when inside the body of Meta ? Should I use some global var instead of object parameter (as it is introduced only to store value temporarily) ?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

飘落散花 2024-10-04 03:21:56

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

为什么不能在 __init__ 中完成这一切?您可以从那里修改 self.fields

You can't do anything dynamic within Meta. That's not what it's for.

Why can't you do it all within __init__? You can modify self.fields from there.

臻嫒无言 2024-10-04 03:21:56

正如 Daniel 提议的那样,我将整个内容移至 __init__

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

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

Just as Daniel proposed, I moved the whole thing to __init__ :

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

    if type != 2:
        self.fields.pop("price")
    else:
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文