0

I'm trying to create dynamic form with corresponding fields using following code. But getting problem while submiting value.

If i entered blank value then error is :

Attribute Error:
'module' object has no attribute ''

in forms.py, and if I entered value for salary then error is:

Attribute Error:
'module' object has no attribute '100000'

in forms.py

Here is forms.py

from django import forms

class ContextForm(forms.Form):

         def __init__(self. rdict, *args, **kwargs):
               super(ContextForm, self).__init__(*args, **kwargs)
               for key in rdict.keys():
                     self.fields['%s' % str(key)] = getattr(forms,rdict.get(key))()



rdict = {'address': 'CharField','phone': 'CharField', 'Salary': 'IntegerField','first name': 'CharField','last name':'CharField'}

c = ContextForm(rdict)
Rafał Rawicki
  • 22,324
  • 5
  • 59
  • 79
Sweet Girl
  • 21
  • 1
  • 4

2 Answers2

0

I'm assuming your view code looks like this:

c = ContextForm(request.POST, rdict)

If you replace it with:

 c = ContextForm(rdict, request.POST)

it works just fine. For explanation read Python normal arguments vs. keyword arguments.

Community
  • 1
  • 1
Martin
  • 2,135
  • 8
  • 39
  • 42
0

First of all, there is an error in your forms.py:

$ python forms.py
  File "forms.py", line 5
    def __init__(self. rdict, *args, **kwargs):
                     ^
SyntaxError: invalid syntax

Then, I believe the problem is the following. Maybe, you're trying to create the form with the code like this:

new_form = ContextForm(request.POST, something_else)

Therefore, if your request.POST is something like this:

{'some_field': '100000'}

Then in this line:

self.fields['%s' % str(key)] = getattr(forms,rdict.get(key))()

forms is a module object, key is 'some_field', so rdict.get(key) is '100000' and

getattr(forms,rdict.get(key))()

is equivalent to:

getattr(forms, '100000')()

which is definitely not OK.

stepank
  • 456
  • 5
  • 8
  • yes sir, its coming something like u said and i want this should be appear getattr(forms, 'XXXField'). How could i get this? – Sweet Girl Mar 19 '12 at 11:54
  • does `ContextForm(rdict, request.POST, anything_else_you_normally_pass_to_a_form_constructor)` help? – stepank Mar 19 '12 at 13:04
  • no,passing only dictionary. if request.method=='POST': form = ContextForm(request.POST,rdict) – Sweet Girl Mar 20 '12 at 05:25
  • why do you pass `rdict` as second argument? according to `ContextForm` definition it must be first argument. – stepank Mar 20 '12 at 07:46
  • **thank you** for your co-ordination. As u said i've tried with rdict as 1st argument and now its working properly. Its creating dynamic form as well as its cheking for their field types – Sweet Girl Mar 20 '12 at 08:19