如何从给定的选择初始化 django 表单数据类型字段



首先:我无法找到这个问题的正确标题。

无论如何,问题是:

我必须在模板上填写表单,此表单的字段取决于用户。例如,您将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()'.我也使用这个返回值,但它不起作用。艾米解决这个问题?

最简单的方法是创建表单类并包含所有可能选择的字段。然后在此类中编写一个构造函数并隐藏您不想出现的字段。构造函数必须采用一个参数,指示我们需要哪些字段。将此参数存储在表单中并在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)

最新更新