I am using Django everyday now for three month and it is really great. Fast web application development.
I have still one thing that I cannot do exactly how I want to. It is the SelectField and SelectMultiple Field.
I want to be able to put some args to an option of a Select.
I finally success with the optgroup :
class EquipmentField(forms.ModelChoiceField):
def __init__(self, queryset, **kwargs):
super(forms.ModelChoiceField, self).__init__(**kwargs)
self.queryset = queryset
self.to_field_name=None
group = None
list = []
self.choices = []
for equipment in queryset:
if not group:
group = equipment.type
if group != equipment.type:
self.choices.append((group.name, list))
group = equipment.type
list = []
else:
list.append((equipment.id, equipment.name))
But for another ModelForm, I have to change the background color of every option, using the color property of the model.
Do you know how I can do that ?
Thank you.
What you need to do, is to change the output which is controlled by the widget. Default is the select widget, so you can subclass it. It looks like this:
It's a lot of code. But what you need to do, is to make your own widget with an altered render method. It's the render method that determines the html that is created. In this case, it's the
render_options
method you need to change. Here you could include some check to determine when to add a class, which you could style.Another thing, in your code above it doesn't look like you append the last group choices. Also you might want to add an
order_by()
to the queryset, as you need it to be ordered by the type. You could do that in the init method, so you don't have to do it all over when you use the form field.render_option
has been removed from Django 1.11 onwards. This is what I did to achieve this. A little bit of digging and this seems straightforward and neat. Works with Django 2.0+The form:
The output which I needed is as:
You should not mess with form fields for adding some custom attributes to the rendered html tag. But you should subclass and add a these to the Widget.
From the docs: customizing-widget-instances
You can submit
attrs
dictionary to the form Widgets, that render as attributes on the output form widgets.http://code.djangoproject.com/browser/django/trunk/django/newforms/widgets.py?rev=7083
As seen under the class Select(Widget):, there is no way to add the style attribute to an option tag. To this, you will have to subclass this widget and add such functionality.
The class Select(Widget): definition only adds style attribute to the main select tag.