开发者

Get parameters of object in metaclass of this object

开发者 https://www.devze.com 2023-01-19 13:17 出处:网络
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

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

    开发者_C百科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


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.


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:
0

精彩评论

暂无评论...
验证码 换一张
取 消