Django & JavaScript Select2 - Search and Select for related keys

When you have a relational key in django models and you try to render the related model with a model.form, this creates a select drop down. Sometimes you may have many related objects and this can be a nightmare to scroll and find the specific option you want.

Well look no further! Javascript select2 is for you!

Add the CDN for javascript select2 either to the head of the base or to the child template between the appropriate block tags:

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

Simply right click on the auto rendered form element from the form with dev tools, identify the elements id.

Next add the following javascript into the bottom of the template that requires the search & select.

<script>
$(document).ready(function() {
    $("#unique_id").select2();
})
</script>

You will need to add a script tag for the current jQuery version. One used for this document was:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js" integrity="sha512-aVKKRRi/Q/YV+4mjoKBsE4x3H+BkegoM/em46NNlCqNTmUYADjBbeNefNxYV7giUp0VxICtqdrbqU7iVaeZNXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Wallah, like magic your massive scrolling select field now has a search input field that allows for quicker searching!

Avatar for Daisy McGirr

Written by Daisy McGirr

Software Engineer & Student Mentor

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.