简体   繁体   English

如何从给定的选项初始化django-form数据类型字段?

[英]How to initialize django-form data type field from a given choices?

First of all: I am not able to find out the proper Title of this question. 首先:我无法找到这个问题的正确标题。

Anyhow the question is: 无论如何问题是:

I have to fill a form at template and the fields of this form are user dependent. 我必须在模板上填写表单,并且此表单的字段取决于用户。 For example you passes integer (integer is not a datatype) as a parameter to the method and it should returns like this: 例如,您将integer (整数不是数据类型)作为参数传递给方法,它应该返回如下:

fileds = forms.IntegerField()

If you pass bool then it should like this: 如果你通过bool那么它应该是这样的:

fields = forms.BooleanField()

So that i can use them to create my form. 这样我就可以用它们来创建我的表单了。 I tried with this code but it returns into the form of string. 我试过这个代码,但它返回到字符串的形式。

Some.py file: 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

When i print the field it prints 'forms.BooleanField()' . 当我打印字段时,它会打印'forms.BooleanField()' I also use this return value but it didn't work. 我也使用这个返回值,但它没有用。 Amy solution to this problem? 艾米解决了这个问题?

The simpliest way is to create your form class and include fields for all possible choices to it. 最简单的方法是创建表单类并包含所有可能选择的字段。 Then write a constructor in this class and hide the fields you don't want to appear. 然后在此类中编写构造函数并隐藏您不想显示的字段 The constructor must take a parameter indicating which fields do we need. 构造函数必须使用一个参数来指示我们需要哪些字段。 It can be useful to store this parameter in the form and use it in clean method to correct collected data accordingly to this parameter. 将此参数存储在表单中并在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)

In your controller: 在你的控制器中:

option = 'bool'
form = Your_form(option=option)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM