I have a ModelForm that I'm rendering in the template with django-widget-tweaks. I have a ChoiceField select that prints out something like this:
<select>
<option value="object.id">object.name</option>
</select>
But for Javascript manipulation purposes, I need the following:
<select>
<option value="object.id" class="object.otherPropery">object.name</option>
</select>
django-widget-tweaks has an add_class function, but it only adds a class to the select box, not the contained options.
I have also tried rolling my own select box:
<select>
{% for object in form.object_field %}
<option value="{{ object.id }}" class="{{ object.otherProperty }}">{{ object.name }}</option>
{% endfor %}
</select>
But when the form does not validate and errors are returned, the option the user had selected previously gets reset back to the default (first) option (this does happen with django-widget-tweaks).
I have also tried overriding the render_option
and render_options
fields of the Select widget, but the additional properties of the object are not being passed to those functions.
I feel like there's a simple solution for what I'm trying to do. Any help would be much appreciated!
I guess you can do something like this (note the 'if' tag):
<select>
{% with value=form.object_field.value %}
{% for object in form.object_field %}
<option
value="{{ object.id }}"
class="{{ object.otherProperty }}"
{% if object.id == value %}selected="selected"{% endif %}
>
{{ object.name }}
</option>
{% endfor %}
{% endwith %}
</select>
Although the if condition might not result in a true result when it should, if the object.id
is a integer because the value
would always be a string for a already submitted form (all the values in the POST/GET query data are strings). But if the value comes from the 'initial_data' it would be integer.
For such cases you may update your 'if' tag as follows:
{% if object.id|slugify == value|slugiy %}selected="selected"{% endif %}
Making the final code as follows:
<select>
{% with value=form.object_field.value %}
{% for object in form.object_field %}
<option
value="{{ object.id }}"
class="{{ object.otherProperty }}"
{% if object.id|slugify == value|slugify %}selected="selected"{% endif %}
>
{{ object.name }}
</option>
{% endfor %}
{% endwith %}
</select>