set the css class of a form widget based on the data

22 views
Skip to first unread message

Michael

unread,
Nov 12, 2014, 8:25:14 PM11/12/14
to django...@googlegroups.com
Hi,

The ``attrs`` attribute of a widget allows to define the html attributes. For example, setting it to ``widget.attrs['class'] = 'class1 class2'`` will add ``class="class1 class2"`` on the rendered widget.

However, how can I set them based on the data? I display an update form and I'd like to change the CSS class based on the data that is going to be displayed when the form is rendered.

Where could I check for the data in order to change the ``attrs`` property of the widget before it is rendered?

Thanks

Russell Keith-Magee

unread,
Nov 14, 2014, 5:31:09 AM11/14/14
to Django Users
Hi Michael,

The best bet would be to write a custom widget, and override the render() method. render() takes the name of the widget, the value to render, and a dictionary of attr values. In your subclass, you can override this method to inject the additional attributes based on the provided value - something like:

class MyWidget(TextInput):
    def render(self, name, value, attrs=None):
        if value == SPECIAL VALUE:
            attrs['class'] = 'class1 class2'
        return super(MyWidget, self).render(name, value, attrs)

This is an oversimplification - there's a few extra edge cases you'll need to account for - if attrs is none, or if 'class' already exists - but the idea should hopefully make sense.

Yours,
Russ Magee %-)



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/3569acd7-5bec-4df9-8960-4952b3fee8fb%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Michael Palumbo

unread,
Nov 14, 2014, 3:05:58 PM11/14/14
to django...@googlegroups.com
Thanks Russell, that works well.


--
You received this message because you are subscribed to a topic in the Google Groups "Django users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-users/YADHgsrm3Gk/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-users...@googlegroups.com.

To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
Reply all
Reply to author
Forward
0 new messages