【问题标题】:How to initialize django-form data type field from a given choices?如何从给定的选项初始化 django-form 数据类型字段?
【发布时间】:2012-06-17 09:26:05
【问题描述】:

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

不管怎样,问题是:

我必须在模板中填写表格,并且此表格的字段取决于用户。例如,您将integer(整数不是数据类型)作为参数传递给方法,它应该返回如下:

fileds = forms.IntegerField()

如果你通过bool 那么它应该是这样的:

fields = forms.BooleanField()

这样我就可以使用它们来创建我的表单。我尝试使用此代码,但它以字符串的形式返回。

一些.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()'。我也使用了这个返回值,但是没有用。艾米解决这个问题?

【问题讨论】:

  • 为什么不type = dict(choices)[option]? (而且您可能稍后会在某处运行不必要的 eval 而不是 getattr。)

标签: python django django-forms


【解决方案1】:

最简单的方法是创建表单类并包含所有可能选择的字段。然后在这个类中写一个构造函数和你不想出现的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)

【讨论】:

  • 但是我没有像问题这样的额外字段(你给了我一个链接)。我想创建一个新字段,该字段的数据类型是选项变量的值。当用户注册他时,在我的应用程序中。他输入保存在他的用户配置文件模型中的选项值。所以 option 就是那个值。
  • 您是说要包括所有字段。我只是举了一个例子,实际上所有字段都可以选择。所以我不能选择那个选项。 :(
  • 为每种类型创建单独的字段。一个整数字段,一个布尔字段等
  • 我是 Django 的新手。请把基本代码给我好吗?
猜你喜欢
  • 2020-06-29
  • 2011-03-16
  • 2015-06-22
  • 2016-10-23
  • 2012-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多