get_model 相当于 ModelForms 吗?
我有多个 ModelForm 类,每个类代表一个不同的模型。我想要一个通用的“创建”函数,它根据 URL 参数加载指定的模型表单。可以用这个动态加载模型:
model_name = 'TestModel'
m = get_model('AppLabel', model_name)
有谁知道如何为 ModelForms 实现相同的效果,例如:
modelform_name = 'TestModelForm'
f = get_form('AppLabel', modelform_name)
if f.is_valid():
...
我想不出一种方法来使用通用视图来做到这一点 - 它们需要传递 ModelForm,而不是只是它的名字。如果我使用 get_model 获取模型,然后将其传递给通用视图,它将显示一个表单,但我无法排除模型字段。
TIA 提供任何提示
I have a multiple ModelForm classes that each represent a different Model. I would like to have a generic 'create' function that loads the specified model form based on a URL parameter. It is possible to load a model dynamically with this:
model_name = 'TestModel'
m = get_model('AppLabel', model_name)
Does anyone know how I can achieve the same for ModelForms, something like:
modelform_name = 'TestModelForm'
f = get_form('AppLabel', modelform_name)
if f.is_valid():
...
I can not think of a way to do this with generic views - they require the ModelForm to be passed, rather than just its name. If I get the model with get_model then pass that to the generic view it will display a form but I am unable to exclude model fields.
TIA for any tips
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您创建
ModelForm
时,它不会将自身注册到其模型的应用程序中。 (基于经验和快速浏览源代码)。以下是我能想到的一些其他选项:
所有
ModelForm
类都存在于单个模块中:基于该模块在该模块上使用getattr
细绳。ModelForm
分布在许多模型中,并且您拥有合理的 (<30) 表单数量:创建从您期望的表单字符串到 ModelForm 类的字典映射。例如:
您正在处理大量表单:为您的 ModelForm 创建基类,或在运行时替换
BaseModelFormMetaclass
。您必须“自动”处理名称冲突、同一Model
的重复ModelForm
等问题,因此请做好应对一些头痛的准备。如果你能成功的话,那就太棒了。就我个人而言(正如您可能看到的),我只会选择选项#2。
When you create a
ModelForm
it does not register itself with its model's app. (Based on experience and a quick browse through the source).Here are some otheroptions I can think of:
All
ModelForm
classes exist in a single module: Usegetattr
on that module based on the string.ModelForm
's are spread out among many models and you have a reasonable (<30) amount of forms:Create a dictionary mapping from form strings you expect to ModelForm classes. For example:
You're dealing with a lot of forms: Create a baseclass for your ModelForm, or replace the
BaseModelFormMetaclass
at runtime. You'll have to deal with issues such as name conflicts, duplicateModelForm
s for the sameModel
"automagically", so prepare for some headaches. It would be pretty rad if you could pull it off.Personally (as you can probably see), I'd just go with option #2.
另一种方法是用名为
forms
的包替换forms.py
。然后,在该包内的__init__.py
中,导入所有ModelForm
。然后你可以使用 sdolan 的选项#1。
An alternate method for this is to replace
forms.py
with a package calledforms
. Then, in__init__.py
within that package, import all yourModelForm
s.Then you can use sdolan's Option #1.