3

It is a follow up to this question and answer. My question now is, when I have a ModelMultipleChoiceField in my form how do I access all of the model fields of a passed queryset in template?

Currently my form is:

class CarChoicesForm(forms.Form):
    def __init__(self, *args, **kwargs):
        cars = kwargs.pop('cars', None)
        super(CarChoicesForm, self).__init__(*args, **kwargs)
        self.fields['cars']=forms.ModelMultipleChoiceField(queryset=cars,
                                                            widget=forms.CheckboxSelectMultiple)

Template:

<tbody>
{% for choice in form.cars %}
    <tr>
        <td>{{ choice.choice_label }}</td>
        <td><span class="checkbox">{{ choice.tag }}</span></td>
    </tr>
{% endfor %}
</tbody>

It only prints what Car.__str__() provides, but I need other fields to achieve something like this. I tried {{ choice.choice_label.brand }}, etc. with no success.

Community
  • 1
  • 1
makons
  • 522
  • 1
  • 11
  • 27
  • Sounds like y'all need to create a custom widget for this (https://docs.djangoproject.com/en/1.10/ref/forms/widgets/#customizing-widget-instances). Have you explored this option? – Patrick Beeson Jan 19 '17 at 23:28
  • I went through Django code for both the `forms.CheckboxSelectMultiple` and `forms.ModelMultipleChoiceField`. If I understood correctly, choices are generated in `ModelMultipleChoiceField` as tuples of tag and label. Label is obtained from method `label_from_instance(obj)` as a string. I tried to override that method and leave the whole obj as is, but without success. Widget works with choices and not queryset, so if choices are generated in `ModelMultipleChoiceField` in such a way, I don't see how can I solve my problem through widgets. – makons Jan 21 '17 at 14:28
  • I am still a beginner in Django, so I'll try to dig up some more, but this is what I concluded for now. – makons Jan 21 '17 at 14:29

0 Answers0