在django视图中将表单字段作为属性进行访问

时间:2021-06-26 15:57:15

According to the Django tutorial, you should access form fields using cleaned_data dictionary. I'm wondering why I can't access the properties of the form directly? My form validates just fine, but when I try to access it, Django complains that the object does not have the attribute. I added some code below that I hope will help diagnose the problem.

根据Django教程,您应该使用cleaning_data字典访问表单字段。我想知道为什么我不能直接访问表单的属性?我的表单验证很好,但是当我尝试访问它时,Django抱怨该对象没有该属性。我在下面添加了一些代码,希望能帮助诊断问题。

Form:

形成:

class CustomForm(forms.Form):
    description = forms.CharField(widget = forms.TextInput(attrs = {'placeholder' : 'enter some text'}), label = "My form")

View:

视图:

def process_form(request):
    if request.method != 'POST':
        raise Http404

    myForm = CustomForm(request.POST)

    if not myForm.is_valid():
        c = RequestContext(request)
        return render_to_response('home/index.html', {'form' : myForm }, c)

    # debug
    print 'Description: ' + myForm.description # this does NOT work
    # print 'Description: ' + myForm.cleaned_data['description'] # this does work

I get the following error: 'CustomForm' object has no attribute 'description'. Did I miss something in the docs that says I can't do that?

我收到以下错误:'CustomForm'对象没有属性'description'。我是否遗漏了文档中的某些内容,说我不能这样做?

4 个解决方案

#1


13  

The way you define fields using django.forms is just a convenient, declarative syntax; it's not really representative of what the final Form class, or an instance of it, looks like in terms of attributes.

使用django.forms定义字段的方式只是一种方便的声明性语法;它并不能真正代表最终的Form类或它的实例在属性方面的表现。

Forms have a metaclass (without getting too deep into it, a metaclass is to declaring a class using the class keyword as an __init__ method is to creating an instance of a class using parentheses -- a hook to customise the object being created, which in the case of a metaclass, is a class!) which picks off Fields from the form class at definition time and adds them to a base_fields dict. When you instantiate a form, its base_fields are deep-copied to a fields attribute on the instance.

表单有一个元类(没有深入到它,一个元类是使用class关键字声明一个类,因为__init__方法是使用括号创建一个类的实例 - 一个钩子来定制正在创建的对象,在在元类的情况下,是一个类!),它在定义时从表单类中选择Fields,并将它们添加到base_fields dict中。实例化表单时,会将其base_fields深度复制到实例上的fields属性。

One point of confusion might be that you use . to access fields for display in templates -- what's actually happening there is that Django's template engine first attempts to use dictionary-style [] access to resolve property lookups and the base form class defines a __getitem__ method to take advantage of this, looking up the appropriate field from the form instance's fields dict and wrapping it with a BoundField, a wrapper which knows how to use the field and data from the form for displaying the field.

一点困惑可能是你使用。访问字段以便在模板中显示 - 实际上发生的事情是Django的模板引擎首先尝试使用字典样式[]访问来解析属性查找,而基本表单类定义了一个__getitem__方法来利用这一点,查找表单实例的字段中的适当字段用字符串来包装它,并使用BoundField包装它,该包装器知道如何使用字段和表单中的数据来显示字段。

#2


16  

If your form is validated then you can access myForm cleaned_data:

如果您的表单已经过验证,那么您可以访问myForm cleaning_data:

print myForm.cleaned_data.get('description')

If you want to see why you cannot access myForm.description then you can see the data dictionary of your myForm:

如果你想知道为什么你不能访问myForm.description,那么你可以看到你的myForm的数据字典:

print myForm.__dict__

#3


3  

You can access your field trought dict.

你可以访问你的领域tict。

form.__dict__["fields"]["description"]

#4


3  

You can access the fields of a Form instance from its fields attribute.

您可以从其fields属性访问Form实例的字段。

myForm.fields['description']

And some property like label can be accessed like this:

像label这样的属性可以像这样访问:

myForm.fields['description'].label

Not sure how to display the value corresponding. Anybody having idea?

不确定如何显示相应的值。有人有想法吗?

here is my reference

这是我的参考

https://docs.djangoproject.com/en/dev/ref/forms/api/#accessing-the-fields-from-the-form

https://docs.djangoproject.com/en/dev/ref/forms/api/#accessing-the-fields-from-the-form

#1


13  

The way you define fields using django.forms is just a convenient, declarative syntax; it's not really representative of what the final Form class, or an instance of it, looks like in terms of attributes.

使用django.forms定义字段的方式只是一种方便的声明性语法;它并不能真正代表最终的Form类或它的实例在属性方面的表现。

Forms have a metaclass (without getting too deep into it, a metaclass is to declaring a class using the class keyword as an __init__ method is to creating an instance of a class using parentheses -- a hook to customise the object being created, which in the case of a metaclass, is a class!) which picks off Fields from the form class at definition time and adds them to a base_fields dict. When you instantiate a form, its base_fields are deep-copied to a fields attribute on the instance.

表单有一个元类(没有深入到它,一个元类是使用class关键字声明一个类,因为__init__方法是使用括号创建一个类的实例 - 一个钩子来定制正在创建的对象,在在元类的情况下,是一个类!),它在定义时从表单类中选择Fields,并将它们添加到base_fields dict中。实例化表单时,会将其base_fields深度复制到实例上的fields属性。

One point of confusion might be that you use . to access fields for display in templates -- what's actually happening there is that Django's template engine first attempts to use dictionary-style [] access to resolve property lookups and the base form class defines a __getitem__ method to take advantage of this, looking up the appropriate field from the form instance's fields dict and wrapping it with a BoundField, a wrapper which knows how to use the field and data from the form for displaying the field.

一点困惑可能是你使用。访问字段以便在模板中显示 - 实际上发生的事情是Django的模板引擎首先尝试使用字典样式[]访问来解析属性查找,而基本表单类定义了一个__getitem__方法来利用这一点,查找表单实例的字段中的适当字段用字符串来包装它,并使用BoundField包装它,该包装器知道如何使用字段和表单中的数据来显示字段。

#2


16  

If your form is validated then you can access myForm cleaned_data:

如果您的表单已经过验证,那么您可以访问myForm cleaning_data:

print myForm.cleaned_data.get('description')

If you want to see why you cannot access myForm.description then you can see the data dictionary of your myForm:

如果你想知道为什么你不能访问myForm.description,那么你可以看到你的myForm的数据字典:

print myForm.__dict__

#3


3  

You can access your field trought dict.

你可以访问你的领域tict。

form.__dict__["fields"]["description"]

#4


3  

You can access the fields of a Form instance from its fields attribute.

您可以从其fields属性访问Form实例的字段。

myForm.fields['description']

And some property like label can be accessed like this:

像label这样的属性可以像这样访问:

myForm.fields['description'].label

Not sure how to display the value corresponding. Anybody having idea?

不确定如何显示相应的值。有人有想法吗?

here is my reference

这是我的参考

https://docs.djangoproject.com/en/dev/ref/forms/api/#accessing-the-fields-from-the-form

https://docs.djangoproject.com/en/dev/ref/forms/api/#accessing-the-fields-from-the-form