[Answer]-Django show ManyToMany field of model using ModelChoiceField

1👍

You can’t just display a form field on its own. It has to actually be part of a form, which you must instantiate before passing it to the template.

Also note that your method for getting the parent is horribly inefficient: you instantiate every single Parent in the database, just to get one. You should query it directly.

class ParentForm(forms.Form):
     media = forms.ModelChoiceField(Media.objects.none(), widget=forms.Select())
     def __init__(self, *args, **kwargs):
         parent = kwargs.pop('parent')
         super(ParentForm, self).__init__(*args, **kwargs)
         self.fields['media'].queryset = parent.media.all()

def my_view(request):
    parent = Parent.objects.filter(name=request.session['current_parent'])
    form = ParentForm(parent=parent)
    return render_to_response('tab.html', {'media_form': form}) 

Alternatively, it might be easier to just pass the parent object to the template and then construct the select box manually:

 <select name='media'>
 {% for media in parent.media.all %}
     <option value='{{ media.ident }}'>{{ media.name }}</option>
 {% endfor %}
 </select>

Leave a comment