How to have a multiple select field in django in t

2019-08-26 11:31发布

Any help is greatly appreciated, I am a newbie in django.

class studentRegister(forms.Form):
courseList = forms.ModelMultipleChoiceField(queryset=Courses.objects.all())

Thank you and appreciate your time, I just want to modify this type of form so I can multiple select two or more options at a time and that returns in a list maybe?

2条回答
我只想做你的唯一
2楼-- · 2019-08-26 12:06

I think you can use the SelectMultiple widget. Source

class studentRegister(forms.Form):
    courseList = forms.ModelMultipleChoiceField(queryset=Courses.objects.all(), widget=forms.SelectMultiple)

If this does not fit your needs, you can try using this snippet.

查看更多
爷的心禁止访问
3楼-- · 2019-08-26 12:13

One idea is work with Bootstrap classes and Python.

forms.py

class yourForm(forms.Form):
options = forms.MultipleChoiceField(
    choices=[(option, option) for option in
             Options.objects.all()], widget=forms.CheckboxSelectMultiple(),
    label="myLabel", required=True, error_messages={'required': 'myRequiredMessage'})

view.py

def anything(...):
    (...)
    form = yourForm( )
    (...)
    return render(request, "myPage.html", {'form': form})

myPage.html

(...)
{% csrf_token %}
    {% for field in form %}
        <div class="col-md-12 dropdown">
            <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">{{ field.label_tag }}
                <span class="caret"></span>
            </button>
            <div class="dropdown-menu">
                <div><a href="#">{{ field }}</a></div>
            </div>
        </div>
    {% endfor %}
(...)
查看更多
登录 后发表回答