简体   繁体   中英

DJANGO: Add “select all” choice option to ModelMultipleChoiceField?

Is there a way to add additional choices to a ModelMultipleChoiceField? Specifically, I want to add a "Select All" option instead of an End-User having to select all of the choices individually.

Current Model Form:

class QueryForm(forms.Form):
    book = forms.ModelMultipleChoiceField(queryset=Book.objects.all())

I want something like this:

class QueryForm(forms.Form):
    book = forms.ModelMultipleChoiceField(choices=(('Select All', 'Select All'),(Book.objects.all()))

How can I add the Select All option to Model Multiple Choice Field?

Is this in the Django admin or in your own form? If it's the admin, the easiest solution is to simply add the field to ModelAdmin.filter_horizontal or ModelAdmin.filter_vertical . The special field that the Django admin will use has a "Choose All" option builtin.

If it's your own form, JS is your best bet as @AdamKG recommends. Given the following:

<div class="field">
    <select multiple="multiple" name="my_field">
        <option value="something">Something</option>
        ...
    </select>
    <a href="#" class="select-all">Select All</a>
</div>

This bit of jQuery should do the trick:

$('.select-all').click(function(){
    $('option', $(this).parent()).attr('selected', 'selected');
});

You will need to convert your ModelMultipleChoiceField to a MultipleChoiceField that gets its choices from the related model in __init__() . Add a "Select All" option with a sentinel (eg "all") instead of the PK that you will get from the actual models. Then just detect this in the POST view and set things appropriately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM