get_model是否等效于ModelForms? [英] get_model equivalent for ModelForms?

查看:52
本文介绍了get_model是否等效于ModelForms?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个ModelForm类,每个类代表一个不同的Model.我想要一个通用的创建"功能,该功能基于URL参数加载指定的模型形式.可以通过以下方式动态加载模型:

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)

有人知道如何为ModelForms实现相同的目标吗?

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():
    ...

我想不出使用通用视图执行此操作的方法-它们要求传递ModelForm,而不仅仅是传递其名称.如果我使用get_model获取模型,然后将其传递给通用视图,它将显示一个表单,但我无法排除模型字段.

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的任何提示

推荐答案

创建 ModelForm 时,它不会在其模型的应用程序中注册自己.(基于经验并快速浏览源代码.)

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:

  1. 所有 ModelForm 类都存在于单个模块中:在基于字符串的模块上使用 getattr .

  1. All ModelForm classes exist in a single module: Use getattr on that module based on the string.

ModelForm 分布在许多模型中,并且您有合理的(<30)数量的表单:从期望的表单字符串到ModelForm类创建字典映射.例如:

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:

from some_app.forms import FirstModelForm
from another_app.forms import SecondModelForm
from additional_app.forms import FirstModelForm as AdditionalAppFirstModelForm # Will allow for managing conflicting names easily.

form_mapping = {
    'FirstModelForm': FirstModelForm,
    'SecondModelForm': SecondForm,
    'AdditionalAppFirstModelForm': AdditionalAppFirstModelForm,
}

request_form_class = request.POST.get('form_class')
f = form_mapping.get(request_form_class)(request.POST)

if f.is_valid():
    f.save()

  • 您要处理的表格很多:为您的ModelForm创建基类,或者在运行时替换 BaseModelFormMetaclass .您将不得不处理名称冲突,自动"为同一 Model 复制相同的 ModelForm 的问题,因此请为头痛做准备.如果您能将它拉下来,那就太好了.

  • 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, duplicate ModelForms for the same Model "automagically", so prepare for some headaches. It would be pretty rad if you could pull it off.

    就个人而言(您可能会看到),我只选择选项2.

    Personally (as you can probably see), I'd just go with option #2.

    这篇关于get_model是否等效于ModelForms?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆