loading...

Builtin Select2 Widget in Django Admin

connorbode profile image Connor Bode ・1 min read

Just discovered an excellent built-in feature for Django Admin, released in version 2.0.

Turns out, there is

Let's say in models.py, you have two models: Person and Problem. A person can have many problems..

So we build a simple PersonAdmin:

from django.contrib import admin
from . import models


@admin.register(models.Person)
class PersonAdmin(admin.ModelAdmin):
    pass

and we end up with something like this:

Alt Text

Now, as you can see, Dave has a leaky faucet, his shoe laces are undone and he's broke. Poor guy.

But let's be serious, this ManyToMany widget sucks. If that list grows it's going to be a huge pain in the ass to select many items.

Select2 is a great option.. and turns out Django added it into the base install in version 2.0. Thx guys!

Make some small modifications to admin.py:

from django.contrib import admin
from . import models


@admin.register(models.Person)
class PersonAdmin(admin.ModelAdmin):
    autocomplete_fields = ['problems']


@admin.register(models.Problem)
class ProblemAdmin(admin.ModelAdmin):
    search_fields = ['description']

and voila:

Alt Text

Dave still can't tie his shoes, and he's wetting the bed now. But at least he figured out how to have a usable ManyToMany widget in his Django Admin!


Hope this quick tip helps you out. Follow me here on dev.to or on Twitter @connorbode for more Django, Python, Linux, etc. as I build & learn.

Discussion

pic
Editor guide
Collapse
lewiskori profile image
Lewis kori

😍Just what I needed. Was having a tough time getting those manytomany relationships play nice. Cool post.