Accessing form fields as properties in a django view

后端 未结 4 603
时光说笑
时光说笑 2020-12-29 09:01

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 for

相关标签:
4条回答
  • 2020-12-29 09:34

    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.

    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.

    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.

    0 讨论(0)
  • 2020-12-29 09:40

    You can access your field trought dict.

    form.__dict__["fields"]["description"]
    
    0 讨论(0)
  • 2020-12-29 09:43

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

    myForm.fields['description']
    

    And some property like label can be accessed like this:

    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

    0 讨论(0)
  • 2020-12-29 09:52

    If your form is validated then you can access myForm cleaned_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:

    print myForm.__dict__
    
    0 讨论(0)
提交回复
热议问题