DEV Community

Connor Bode
Connor Bode

Posted on

5 1

Builtin Select2 Widget in Django Admin

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
Enter fullscreen mode Exit fullscreen mode

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']
Enter fullscreen mode Exit fullscreen mode

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (2)

Collapse
 
lewiskori profile image
Lewis kori

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

Collapse
 
foxy4096 profile image
Adzy

This it the best thing I found in django admin after the django admin itself

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up