Attaching additional information to form fields

I am trying to pass additional information to the fields of a Django form that will be displayed in a template. I tried to override the constructor and add another property to the field:

self.fields['field_name'].foo = 'bar'

but in the template:

{{ form.field_name.foo }}

did not print anything. Does anyone know how to add additional information to a field without overwriting / inheriting form field classes?

+5
source share
1 answer

django.forms.forms, __getitem__() a Form -, BoundField , , , . , , , :

class MyForm(forms.Form):
    def __getitem__(self, name):
        boundfield = super(forms.Form,self).__getitem__(name)
        boundfield.foo = "bar"
        return boundfield

"bar" . , .

, , , .


- , BoundField "field":

class MyForm(forms.Form):
    def __init__(self, *args, **kwargs)
        super(forms.Form, self).__init__(*args, **kwargs)
        self.fields['field_name'].foo = "bar"

foo :

{{ form.field_name.field.foo }}
+6

All Articles