Open filipeximenes opened 8 years ago
I second this! Im using MultipleChoiceField and would like to customize each item.
@sevetseh28 Hello! I also use MultipleChoiceField in my form. How you fixed your problem with customization in template?
I have this issues as well. Was choice fields ever given support? For now I am just detecting the field type and handling it appropriately. It is kind of ugly but works.
{% load widget_tweaks %}
{% for hidden_field in form.hidden_fields %}
{{ hidden_field }}
{% endfor %}
{% if form.non_field_errors %}
<div class="alert alert-danger" role="alert">
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
</div>
{% endif %}
{% for field in form.visible_fields %}
{% if form.is_bound %}
{% if field.errors %}
{% if field|field_type == 'choicefield' %}
{% render_field field class="form-control is-invalid custom-select my-2" %}
{% else %}
{% render_field field class="form-control is-invalid" placeholder=field.help_text %}
{% endif %}
{% for error in field.errors %}
<div class="invalid-feedback">
{{ error }}
</div>
{% endfor %}
{% else %}
{% if field|field_type == 'choicefield' %}
{% render_field field class="form-control is-valid custom-select my-2" %}
{% else %}
{% render_field field class="form-control is-valid" %}
{% endif %}
{% endif %}
{% else %}
{% if field|field_type == 'choicefield' %}
{% render_field field class="custom-select my-2" %}
{% else %}
{% render_field field placeholder=field.help_text %}
{% endif %}
{% endif %}
{% endfor %}
I did it like this, seems to work fine:
<div class="form-group col-md-6">
<label>Species</label>
<select id="species{{ class.id }}" class="form-control">
{% for option in class_form.species %}
{% if option.choice_label == class.species|title %}
<option value="{{ option.choice_label|lower }}" selected>{{ option.choice_label }}</option>
{% else %}
{{ option }}
{% endif %}
{% endfor %}
</select>
</div>
Can anyone confirm that this sort of thing is still required for select fields?
There's no workaround for this that I can find. @autoferrit's response is not accessing the subwidgets, and @masystems' response is using a select menu. We're talking about fields with a widget that has more than one subwidget, like RadioSelect or CheckboxSelectMultiple.
I think there's a fairly minimal fix. When widget_tweaks sees a BoundWidget instead of a BoundField, the method to wrap would be tag(), rather than as_widget(). @jazzband, will you accept a PR for this?
See the attached for an implementation. I guess I'll put in a PR, at some point. patched_widget_tweaks.py.txt
Ping! I have the same problem. Any update?
Still relevant – PR has been available for a while now: https://github.com/jazzband/django-widget-tweaks/pull/122
I'm also trying to do this.
It's possible to render choice fields this way:
This gives more control over the generated HTML. It's not currently possible to use widget tweaks template tags in this case. Eg.: