[Solved]-Django Admin: How to customize autocomplete_fields width to adapt to the content?

8👍

Django 3.0.9:

forms.py

from django import forms
from django.contrib import admin
from django.contrib.admin.widgets import AutocompleteSelect

from .models import MyModel

    class MyModelForm(forms.ModelForm):
        class Meta:
            fields = ('my_field', )
            widgets = {
                'my_field': AutocompleteSelect(
                    MyModel.my_field.field.remote_field,
                    admin.site,
                    attrs={'style': 'width: 400px'}  # You can put any width you want.
                ),
            }

admin.py

from django.contrib import admin

from .forms import MyModelForm


MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm
👤CentOS

6👍

You can pass data-* attributes to select2 by including them in the autocomplete widget’s attrs. One way to do this is to initialize the widget yourself using a custom form.

Note that if you also include the field in autocomplete_fields then the widget will be initialized by your ModelAdmin instance and your custom initialization won’t have any effect.

Also note that the AutocompleteSelect and AutocompleteSelectMultiple widgets require a couple of positional arguments.

Something like this should work:

from django import forms
from django.contrib import admin
from django.contrib.admin.widgets import AutocompleteSelect

class MyForm(forms.ModelForm):
    class Meta:
        widgets = {
            'my_field': AutocompleteSelect(
                MyModel._meta.get_field('my_field').remote_field,
                admin.site,
                attrs={'data-dropdown-auto-width': 'true'}
            ),
        }

class MyAdmin(admin.ModelAdmin):
    #autocomplete_fields = ['my_field']
    form = MyForm
👤DanS

Leave a comment