Skip to content Skip to sidebar Skip to footer

How To Have A Multiple Select Field In Django In The Form Of A Drop Down Box

Any help is greatly appreciated, I am a newbie in django. class studentRegister(forms.Form): courseList = forms.ModelMultipleChoiceField(queryset=Courses.objects.all()) Thank you

Solution 1:

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 %}
(...)

Solution 2:

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.


Post a Comment for "How To Have A Multiple Select Field In Django In The Form Of A Drop Down Box"