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?
According to django.forms.forms
, the __getitem__()
method 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 hard-coded 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 an 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"
Then, to access foo
in a template:
{{ form.field_name.field.foo }}
精彩评论