Автодополнение в Django Admin

Для реализации автозаполнения в админ-панели Django можно использовать атрибуты поля autocomplete_fields и search_fields в классе модели.

Атрибут autocomplete_fields позволяет указывать поля, для которых будет доступна функция автозаполнения.


from django.contrib import admin
from .models import MyModel

class MyModelAdmin(admin.ModelAdmin):
    autocomplete_fields = ['foreign_key_field']

admin.site.register(MyModel, MyModelAdmin)

В данном примере, поле с внешним ключом foreign_key_field будет иметь функцию автозаполнения.

Атрибут search_fields позволяет указывать поля, которые будут использоваться для поиска во время автозаполнения.


from django.contrib import admin
from .models import MyModel

class MyModelAdmin(admin.ModelAdmin):
    search_fields = ['field1', 'field2']

admin.site.register(MyModel, MyModelAdmin)

В данном примере, при автозаполнении будет осуществляться поиск по полям field1 и field2.

Детальный ответ

Autocomplete in Django Admin

Autocomplete is a powerful feature that allows users to quickly search and select options from a large set of choices. In Django Admin, autocomplete can be used to enhance the user experience when managing data in the admin interface. In this article, we will explore how to implement autocomplete functionality in Django Admin.

Step 1: Install Required Libraries

Before we can start implementing autocomplete in Django Admin, we need to install the necessary libraries. Django Autocomplete Light is a popular library that provides autocomplete functionality in Django. To install it, use the following command:

pip install django-autocomplete-light

Step 2: Define Autocomplete Model

Next, we need to define the model that will be used for autocomplete. This model should contain the fields that we want to search and select from in the admin interface. For example, if we have a model named Person with fields name and email, we can define an autocomplete model as follows:

from dal import autocomplete

class PersonAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        qs = Person.objects.all()
        
        if self.q:
            qs = qs.filter(name__icontains=self.q) | qs.filter(email__icontains=self.q)
        
        return qs

In the above code, we define a class named PersonAutocomplete that extends the Select2QuerySetView class provided by Django Autocomplete Light. The get_queryset method is responsible for returning the queryset of objects that match the search term entered by the user. In this example, we filter the queryset based on the name and email fields.

Step 3: Register Autocomplete Model

Once we have defined the autocomplete model, we need to register it with Django Admin. This can be done by modifying the admin.py file of your Django app:

from django.contrib import admin
from .models import Person
from .autocomplete import PersonAutocomplete

class PersonAdmin(admin.ModelAdmin):
    autocomplete_fields = ['name']

admin.site.register(Person, PersonAdmin)

admin.autodiscover()
autocomplete_light.registry.register(Person, PersonAutocomplete)

In the above code, we import the Person model and the PersonAutocomplete class. We then create a PersonAdmin class that extends the admin.ModelAdmin class. The autocomplete_fields attribute is used to specify the fields that should use autocomplete in the admin interface. In this example, we specify that the name field should use autocomplete.

Finally, we register the Person model with the PersonAdmin class and register the Person model with the PersonAutocomplete class using the register method provided by Django Autocomplete Light.

Step 4: Test Autocomplete in Admin Interface

Once we have completed the above steps, we can test the autocomplete functionality in the admin interface. When adding or editing a Person object, the name field will now have autocomplete functionality. As the user types in the field, a dropdown will appear with matching options, allowing the user to easily select the desired option.

For example, if we have a Person object with the name "John Doe", typing "John" in the name field will display a dropdown with the option "John Doe". The user can then select this option instead of manually typing the entire name.

By implementing autocomplete in Django Admin, we can greatly improve the user experience when managing data in the admin interface. Users can quickly search and select options from a large set of choices, making data management more efficient and user-friendly.

Видео по теме

Django : Django Admin: change select box for foreign key to search autocomplete, like search object

Auto Search Django | Django Autocomplete Search | Auto complete Input Django | Newton School

Django Autocomplete with jQuery UI | AJAX | Search | Filter from Database | Tutorial | Code Band

Похожие статьи:

Создание сайта на Django: отправка сообщений

Автодополнение в Django Admin

Управляйте py django для эффективного разработки веб-приложений