首先:我无法找到这个问题的正确标题。
无论如何问题是:
我必须在模板上填写表单,此表单的字段取决于用户。例如,您将integer
(整数不是数据类型)作为参数传递给方法,它应该像这样返回:
fileds = forms.IntegerField()
如果你通过了bool
,那么它应该是这样的:
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()'
。我也使用这个返回值,但它没有用。艾米解决了这个问题?
答案 0 :(得分:2)
最简单的方法是创建表单类并包含所有可能选择的字段。然后在此类中编写构造函数,并且不希望出现hide the fields。构造函数必须使用一个参数来指示我们需要哪些字段。将此参数存储在表单中并在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)