我可以让模型知道它的 ModelForm 吗?
我有一个标准的模型和模型表单设置。我希望能够从我的模型返回 ModelForm 对象。这涉及到不可能的循环引用。我认为既然 Django 允许外键模型表示为字符串,也许可以做类似的事情。目前我正在这样做:
class Thing(models.Model):
stuff = models.TextField()
def get_form(self):
return getattr(sys.modules[__name__], "ThingForm")(self)
class ThingForm(ModelForm):
class Meta:
model = Thing
它有效。但我觉得这样做给我自己和我的家人带来了耻辱。一定有更荣耀的方式。
顺便说一句,我想这样做是因为我使用 ContentTypes 创建通用外键,所以我的视图代码不知道模型在静态上下文中是什么类。
I have a standard Model and ModelForm set-up. I want to be able to return the ModelForm object from my Model. This involves an impossible circular reference. I thought that since Django allows foreign key models to be expressed as strings, perhaps it's possible to do something similar. At the moment I'm doing this:
class Thing(models.Model):
stuff = models.TextField()
def get_form(self):
return getattr(sys.modules[__name__], "ThingForm")(self)
class ThingForm(ModelForm):
class Meta:
model = Thing
It works. But I feel that in doing this I bring shame upon myself and my family. There must be a more honourable way.
By the way, I want do to this because I'm using ContentTypes to create generic foreign keys, so my view code doesn't know what class the model is in the static context.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这……不是不可能的循环引用。仅当运行引用名称的代码时才会查找名称。
That's... not an impossible circular reference. Names are only looked up when the code that references them is run.