Django 3.1: Access objects in template of ModelChoiceField

254 views Asked by At

Using Django 3.1 and I'm struggling with a basic tasks.

I've got a form with a field like this:

forms.ModelChoiceField(queryset=StorageSpace.objects.filter(visible=True), widget=forms.RadioSelect)

I would like to do this in my view:

{% for space in form.available_spaces %}
        <label class="btn btn-outline-primary">
            <input value="{{ space.id }}" data-storage-price={{ space.price }}>{{ space.title }}
        </label>
{% endfor %}

But this doesn't work. How can I access the attributes of my objects for each choice? Can't be that difficult, can it? I really need to set the data attribute, otherwise I would just use{{space}}.

1

There are 1 answers

0
Remo On
form.available_spaces.field.queryset

lets you access the object behind the choice-field. As simple as that.