获取该对象元类中对象的参数
我的问题是 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能在 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 modifyself.fields
from there.正如 Daniel 提议的那样,我将整个内容移至
__init__
:Just as Daniel proposed, I moved the whole thing to
__init__
: