tags:

views:

21

answers:

1

Hi,

I'm trying to pass on additional information to fields of a Django form to be displayed in a template. I tried to override the constructor and add another property to the field like this

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

but in the template this

{{ form.field_name.foo }}

didn't print anything. Does anyone know how to add additional information to a field without rewriting/inheriting the forms field classes?

Cheers, Max

A: 

According to django.forms.forms, the _getitem_() property of a Form creates something called a BoundField out of the field before returning it, thus stripping it of whatever changes you made. If you really want to insert more functionality into that, override that method to do stuff to the bound field before returning it:

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

Then, bar will appear for all fields in that form... you can also make a function and call that instead, to make it more than just a hardcoded string.

While it's more standard to add more fields, or to add properties to the form itself, if you have a whole new class of info that every field needs to contain, this may do it for you.

Another way to get the same thing is to edit the foo attribute of the field, then access it via the BoundField's "field" attribute:

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

And then:

 {{ form.field_name.field.foo }}
eruciform
Thanks for the explanation. I tried the latter of the two approaches and it worked like a charm - thanks again.
Max