如何将字符串转换为表单?
在模型中你可以只使用这一行。
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/