如何将字符串转换为表单?
在模型中你可以只使用这条线。
model = apps.get_model(app_label='app_label', model_name='str_model')
Run Code Online (Sandbox Code Playgroud)
我有 3 种形式,即:
并愿意这样做。
type = "customer"
form = "Fund_"+type #that would make "Fund_customer"
form = apps.get_form(form) #I wonder if there's a function like this.
Run Code Online (Sandbox Code Playgroud)
我只是不想做if条件来实现这一点。
Django 没有像模型那样的表单类注册表。
最简单的解决方案是制作一个字典,其中包含按名称键控的表单
forms = {
'customer': Fund_customer,
'employee': Fund_employee,
'supplier': Fund_supplier,
}
Run Code Online (Sandbox Code Playgroud)
然后进行字典查找以获取表单类。
form_class = forms[form_type]
Run Code Online (Sandbox Code Playgroud)
添加新表单时需要记住更新字典,但此解决方案的优点是它比创建表单类注册表要简单得多。
如果所有表单都在同一个 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
839 次 |
| 最近记录: |