[Answered ]-Django admin โ€“ manytomany filter_horizontal โ€“ limit to three choices

2๐Ÿ‘

โœ…

You can achieve it by using jquery, this would save all the serverside overhead;

in your model admin add this:

 class Media:
        js = ('PATHA_AFTER_STATIC/limitchoice.js', )

Put your limitchoice.js in the statics/ folder (credit to: https://stackoverflow.com/a/2046293/288387)

$("id_MODELNAME_to").on("change", "option", function () {
    if ( 3 <= $(this).siblings(":selected").length ) {
        $(this).removeAttr("selected");
        alert("Only 3 choices allowed");
    }
});โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹

Note the id of your manytomany field id_MODELNAME_to wich points to the second box.

Hope it helps

๐Ÿ‘คelsadek

Leave a comment