简体   繁体   中英

getting error while submiting in dynamic form in django

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)

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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