0

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:

fileds = forms.IntegerField()

If you pass bool then it should like this:

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:

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()'. I also use this return value but it didn't work. Amy solution to this problem?

Amit Pal
  • 10,604
  • 26
  • 80
  • 160
  • Why not `type = dict(choices)[option]`? (And you probably run unnecessary `eval` somewhere later instead of `getattr`.) – dhill Mar 19 '15 at 14:22

1 Answers1

2

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.

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)
Community
  • 1
  • 1
Pavel Strakhov
  • 39,123
  • 5
  • 88
  • 127
  • But i don't have extra field like the question (you gave me a link). I want to create a new field and the data type to that field is the value of option variable. In my app when user is registering him. He enter a option value which save in his user profile model. So the ***option*** is that value. – Amit Pal Jun 17 '12 at 09:43
  • And you are saying to include all the fields. I just gave a example, in actual all field is available in choices. So i can't choose that option. :( – Amit Pal Jun 17 '12 at 09:46
  • Create separate field for each type. One integer field, one boolean field etc. – Pavel Strakhov Jun 17 '12 at 09:46
  • I am newbie in Django. Would you please give me the basic code? – Amit Pal Jun 17 '12 at 09:48