[Django]-How to use django-select2 widgets in django admin site?

11👍

Since Django 2.0., we can use autocomplete_fields.

autocomplete_fields is a list of ForeignKey and/or ManyToManyField
fields you would like to change to Select2 autocomplete inputs.

ModelAdmin(is parent of UserAdmin) has the property autocomplete_fields (Django Docs):

from django.contrib.auth.admin import UserAdmin
from django.contrib.auth import get_user_model


User = get_user_model()


class UserAdminInherited(UserAdmin):
    autocomplete_fields = ['worker']
    ...


admin.site.register(User, UserAdminInherited)

You must define search_fields on the related object’s ModelAdmin
because the autocomplete search uses it.

from django.contrib import admin

@admin.register(WorkerModel)
class WorkerModelAdmin(admin.ModelAdmin):
    search_fields = ['model_field']
👤NKSM

Leave a comment