开发者

Django - AttributeError when trying to access a field in a Form

I ha开发者_开发知识库ve a form somewhere:

class FooForm(forms.Form):
    a_field = forms.CharField()
    not_a_field = 'hello world'

When instantiating this, and trying to access the field, I get a

>>> from baz.views import FooForm
>>> f = FooForm()
>>> f.not_a_field
'hello world'
>>> f.a_field
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'FooForm' object has no attribute 'a_field'

What is going on?


The way that Form is designed, the attributes are removed as attributes and added to the fields attribute. This is done so that we can use declarative syntax to define our Form, but can loop through the fields when the time comes.

>>> f = FooForm()
>>> f.fields['a_field']
<django.forms.fields.CharField object at 0x1750350>

You can find the logic for this in two places. django/forms/forms.py contains the class DeclarativeFieldsMetaclass and the method get_declared_fields. These two bits contain the logic to move everything into the fields list.


Form fields are accessable through the 'fields' property.

From shell:

>>> f = FooForm()
>>> f.fields['a_field']

will return:

<django.forms.fields.CharField object at [memory location]>

You won't be able to access the field using f.a_field unless it has a value.


that's because a_field isn't initialized ex:

>>> f.a_field = 'hi'
>>> print f.a_field
'hi'

you have to add data and perform your save() there

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜