django admin 中选择字段的可搜索下拉列表

Searchable drop down for choice field in django admin

我有一个包含大量数据的选择字段,我在管理面板上创建了下拉菜单,但我想要一个可搜索的下拉菜单。

class ItemForm(forms.ModelForm):

   def __init__(self, *args, **kwargs):
       super(PublicUserForm, self).__init__(*args, **kwargs)
       self.fields['city'] = forms.ChoiceField(
       choices = CHOOSE_CITY) 

class ItemAdmin(admin.ModelAdmin):
   form = ItemForm

admin.site.register(Item, ItemAdmin)

我已提交 django-autocomplete-light

提前致谢!

按照以下步骤操作

使用 pip 安装 django autocomplete light

pip install django-autocomplete-light

然后,让 Django 找到我们需要的静态文件,方法是在 INSTALLED_APPSdjango.contrib.admingrappelli 之前添加

'dal',
'dal_select2',
#'grappelli',
'django.contrib.admin',

现在您需要创建一个自动完成视图,该视图将在您搜索时使用过滤后的查询集进行响应。

from dal import autocomplete

from your_app.models import City


class CityAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):

        if not self.request.user.is_authenticated:
            return City.objects.none()

        qs = City.objects.all()

        if self.q:
            qs = qs.filter(name__istartswith=self.q)

        return qs

Note: The base view for autocomplete view should be Select2QuerySetView.

现在注册自动完成视图为视图创建一个named url

from your_app.views import CityAutocomplete

urlpatterns = [
    url(
        r'^city-autocomplete/$',
        CityAutocomplete.as_view(),
        name='city-autocomplete',
    ),
]

您现在可以在项目表单中使用自动完成视图。使用 ModelSelect2 创建小部件

from dal import autocomplete

from django import forms


class ItemForm(forms.ModelForm):
    city = forms.ModelChoiceField(
        queryset=City.objects.all(),
        widget=autocomplete.ModelSelect2(url='city-autocomplete')
    )

    class Meta:
        model = Item
        fields = ('__all__')

现在您可以在管理员中轻松使用它了。

from your_app.forms import ItemForm

class ItemAdmin(admin.ModelAdmin):
   form = ItemForm

admin.site.register(Item, ItemAdmin)

Note: This will work if you have city field as a foreign key in the Item model.


如果 city 是选择字段,您可以 use autocompleting based on a list of Strings

使用 Select2ListView 创建列表视图并覆盖 get_list 方法

class CityAutocomplete(autocomplete.Select2ListView):
    def get_list(self):
        # return all cities name here, it will be auto filtered by super class
        return ['Pune', 'Patna', 'Mumbai', 'Delhi', ...]

如上注册URL,现在修改你的模型形式,使用Select2ListChoiceField

def get_choice_list():
    # all cites to used as chice list
    return ['Pune', 'Patna', 'Mumbai', 'Delhi', ...]


class ItemForm(forms.ModelForm):
    city = autocomplete.Select2ListChoiceField(
        choice_list=get_choice_list,
        widget=autocomplete.ListSelect2(url='city-autocomplete')
    )

    class Meta:
        model = Item
        fields = ('__all__')

按照我们在上面的示例中所做的那样,将此表单添加到 ModelAdmin。