python - Django:如何将字符串转换为形式?

标签 python django

如何将字符串转换为表单?

在模型中你可以只使用这一行。

model = apps.get_model(app_label='app_label', model_name='str_model')

我有 3 种形式,即:

  • Fund_customer
  • Fund_employee
  • 基金供应商

并且愿意这样做。

type = "customer"
form = "Fund_"+type #that would make "Fund_customer"
form = apps.get_form(form) #I wonder if there's a function like this.

我只是不想通过 if 条件来实现此目的。

最佳答案

Django 没有像模型那样的表单类注册表。

最简单的解决方案是制作一个字典,其中的表单按名称键入

forms = {
    'customer': Fund_customer,
    'employee': Fund_employee,
    'supplier': Fund_supplier,
}

然后进行字典查找以获取表单类。

form_class = forms[form_type]

添加新表单时需要记住更新字典,但此解决方案的优点是它比创建表单类注册表简单得多。

如果您的所有表单都在同一个 forms.py 模块中,您可以尝试定义一个使用 getattr 的函数。

from myapp import forms

def get_form_class(form_type):
    class_name = 'Fund_%s' % form_type
    # third argument means it returns None by default instead of raising AttributeError
    return getattr(forms, class_name, None) 

关于python - Django:如何将字符串转换为形式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42141390/

相关文章:

python - 名称 'pytest' 未定义。如何运行testpy?

python - 类型提示指定类型的集合

python - 如何转储 request.POST 到 dict,维护多个值字段?

django - 在保存对象之前处理文件上传

Python 无法导入名称 timegm

python - Tensorflow:属性错误:模块 'tensorflow.python.ops.nn' 没有属性 'softmax_cross_entropy_with_logits_v2'

python - 在 matplotlib 的饼图上组织文本

python - Django 会自动检测最终用户的时区吗?

django, Squash 迁移,太多循环依赖

python - Django 休息 : Retrieving by a different parameter using ModelViewSet