如何在 django 管理站点中使用 django-select2 小部件?

How to use django-select2 widgets in django admin site?

在我的 Django 应用程序中,我修改了用户实体以包含一个工作字段 (OneToOneField)。但是从 django 管理站点来看,该字段产生了如此多的结果,因此登录用户很难 select 一个工作人员。有什么方法可以使用 django 管理站点中的 select2 (ModelSelect2Widget) 小部件吗? 对于任何常规形式,我都按以下方式定义小部件:

from django_select2.forms import ModelSelect2Widget
    class ProcessForm(forms.ModelForm):
        class Meta:
            model = ProcessModel
            exclude = ('id',)
    
            widgets = {
                'name':forms.TextInput(attrs={'class': 'form-control'}),
                'code':forms.TextInput(attrs={'class': 'form-control'}),
                'description':forms.Textarea(attrs={'class': 'form-control'}),
                'geom': LeafletWidget(),
                'product': ModelSelect2Widget(model=ProductModel, queryset=ProductModel.objects.filter(),
                                                search_fields=['name__icontains'],
                                                attrs={'style': 'width: 100%;'}), 
    }

有什么方法可以在管理站点表单中为工作人员字段使用 ModelSelect2Widget 吗? 这是我的代码:

class User(AbstractUser):
    worker = models.OneToOneField(WorkerModel, on_delete=models.CASCADE, 
                related_name="user", verbose_name=_("Trabajador"), null=True, blank=True)

    
    class Meta:
        default_permissions = ()
        verbose_name="Usuario"
        verbose_name_plural="Usuarios"
        permissions = (
            ("secretario", "Secretario(a)"),
            ("director", "Director"),
        
        )
from django.contrib.auth.admin import UserAdmin

class UserAdminInherited(UserAdmin):
    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
        (_('Worker info'), {'fields': ('worker',)}),
        (_('Permissions'), {
            'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions'),
        }),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )

admin.site.register(User, UserAdminInherited)

Django 2.0. 开始,我们可以使用 autocomplete_fields.

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

ModelAdmin(是 UserAdmin 的父级)有 属性 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):
    <b>autocomplete_fields = ['worker']</b>
    ...


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 <b>WorkerModelAdmin</b>(admin.ModelAdmin):
    <b>search_fields = ['model_field']</b>