Chosen selects in the django admin

A frustrating hour wasted and I don’t have enough rep to contribute to this stackoverflow answer, so I’m posting here. To add the jquery chosen widget to the django admin panel (django 1.10, chosen 1.6.2), so that multi select widgets show up properly, you need to do the following:

models.py – Get your manytomany set up

class Threat(models.Model):
    name = models.CharField(max_length=300, unique=True)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['name']


class Species(models.Model): 
    threats = models.ManyToManyField(Threat, blank=True)

admin.py – Register it in the admin site and add custom js and css

class SpeciesAdmin(admin.ModelAdmin):
    class Media:
        # Put your jquery in - automatically included by django but it appears below the chosen.jquery.min.js, adding it again just seems to shift it above
        js = ('//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js', 
              'chosen/chosen.jquery.min.js',
              'chosen_admin.js')
        css = {'all': ('chosen/chosen.min.css','chosen_admin.css')}

admin.site.register(models.Species, SpeciesAdmin)

chosen_admin.js – Easy, just instantiate chosen as you want

$(document).ready(function() {
    options = {
      search_contains: true, // plus whatever else you want 
    }
    $('#id_threats').chosen(options);
});

chosen_admin.css – This was the annoying bit to pinpoint and fix

.field-threats, .field-threats .related-widget-wrapper {
	overflow: visible !important;	
}
.chosen-container-multi .chosen-results {
	width: 100%;
}

Thanks to radtek and bradmontgomery.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>