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="" 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.

$(document).ready(function() {

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

<script src="" 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


Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.