Re: Add attributes (css-class) to formfield
On Wed, Jul 13, 2011 at 6:41 PM, Andreas Pfrengle <a.pfrengle@gmail.com> wrote:
> Hello,
>
> I know about assigning attributes to widgets, like shown here:
> <https://docs.djangoproject.com/en/1.3/ref/forms/widgets/#customizing-
> widget-instances>
> or here:
> <http://stackoverflow.com/questions/401025/define-css-class-in-django-
> forms>
>
> However, I want to assign an additional attribute to a formfield,
> since we want a css class for a div that is wrapped around the
> presentation of a field. I've tried to assign an attribute in the
> form's __init__, like:
>
> self.fields['my_field'].div_css = "test"
>
> If I try to fetch it in the template however, it resolves to an empty
> string (supposedly the attribute doesn't exist):
> {% for field in form.visible_fields %}
> <div class="{{ field.div_css }}" >
> ....
> </div>
> {% endfor %}
>
> Any help or explanation what goes on inside Django is appreciated.
>
> Regards,
> Andreas
All these replies, and none of them have mentioned why your original
approach doesn't work.
When iterating through a form in your template, each field instance
returned is not a field from form.fields, it is a BoundField that
represents the corresponding field from form.fields.
The original field object is available in bfield.field . Therefore,
with your original code, you can do this in the template:
{% for bfield in form.visible_fields %}
<div class="{{ bfield.field.div_css }}" >
....
</div>
{% endfor %}
Cheers
Tom
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home