Volodymyr Kirichinets Volodymyr Kirichinets - 4 months ago 36
HTML Question

Django how to ManyToManyField show in template as Select widget

My models.py:

class Model2(models.Model)
choice_field = models.ManyToManyField(to=Model)


my template.html:

<div>
{{ form.choice_field }}
</div>


I get a values list and can a scroll and choose what I want. But i want to use Select with options for this values in template.

Answer

You can define widget for each field of your model manually. Assuming you using built-in ModelForm your code in forms.py can be something like this:

from django.forms import ModelForm, Select

class Model2Form(ModelForm):
    class Meta:
        model = Model2
        fields = [
            'choice_field',
        ]
        widgets = {
            'choice_field': Select(),
        }