Python 如何从给定的选项初始化django表单数据类型字段?
首先,我找不到这个问题的正确标题 无论如何,问题是: 我必须在模板处填写表格,此表格的字段取决于用户。例如,您将Python 如何从给定的选项初始化django表单数据类型字段?,python,django,django-forms,Python,Django,Django Forms,首先,我找不到这个问题的正确标题 无论如何,问题是: 我必须在模板处填写表格,此表格的字段取决于用户。例如,您将integer(integer不是数据类型)作为参数传递给该方法,它应该如下所示返回: fileds = forms.IntegerField() fields = forms.BooleanField() 如果您通过bool,那么它应该是这样的: fileds = forms.IntegerField() fields = forms.BooleanField() 这样我就可
integer
(integer不是数据类型)作为参数传递给该方法,它应该如下所示返回:
fileds = forms.IntegerField()
fields = forms.BooleanField()
如果您通过bool
,那么它应该是这样的:
fileds = forms.IntegerField()
fields = forms.BooleanField()
这样我就可以用它们来创建我的表单。我尝试使用此代码,但它返回为字符串形式
Some.py文件:
choices = (('bool','BooleanField()'),
('integer','IntegerField()'))
def choose_field():
option = 'bool' # Here it is hardcoded but in my app it comes from database.
for x in choices:
if x[0]==option:
type = x[1]
a = 'forms'
field = [a,type]
field = ".".join(field)
return field
当我打印字段时,它会打印
“forms.BooleanField()”
。我也使用这个返回值,但它不起作用。艾米:这个问题的解决方案是什么 最简单的方法是创建表单类并包含所有可能选项的字段。然后在这个类中编写一个构造函数,你就不想出现了。构造函数必须接受一个参数,该参数指示我们需要哪些字段。将此参数存储在表单中,并在clean
方法中使用它来根据此参数更正收集的数据可能会很有用
class Your_form(forms.ModelForm):
field_integer = forms.IntegerField()
field_boolean = forms.BooleanField()
def __init__(self, *args, **kwargs):
option = kwargs["option"]
if option == "integer":
field_boolean.widget = field_boolean.hidden_widget()
else:
field_integer.widget = field_integer.hidden_widget()
super(Your_form, self).__init__(*args, **kwargs)
在控制器中:
option = 'bool'
form = Your_form(option=option)
但是我没有像这个问题那样的额外字段(你给了我一个链接)。我想创建一个新字段,该字段的数据类型是option变量的值。在我的应用程序中,当用户注册他时。他输入一个保存在用户配置文件模型中的选项值。这个选项就是这个值,你说的是包含所有的字段。我刚才举了一个例子,实际上所有字段都有选择。所以我不能选择这个选项(为每种类型创建单独的字段。一个整型字段,一个布尔型字段等等。我是Django的新手。请给我基本代码好吗?为什么不
type=dict(choices)[option]
?(以后可能会在某处运行不必要的eval
)