Django如何将ManyToManyField在模板中显示为Select小部件

时间:2016-07-22 11:18:14

标签: html django

我的models.py:

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

my views.py:

def func(request):
    if request.method == 'POST':
        form = ModelForm(request.POST)
        if form.is_valid:
            form.save()
        return.........................................
   And so what I need to do with form request?

我的template.html:

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

我得到一个值列表,可以滚动并选择我想要的内容。但我想在模板中使用Select with options for this values。

1 个答案:

答案 0 :(得分:1)

您可以手动为模型的每个字段定义窗口小部件。假设您使用内置ModelFormforms.py中的代码可能是这样的:

from django.forms import ModelForm, Select

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