Django 2.2 - change with of related auto_complete field on admin form

Viewed 306

I'm trying to change the field width of a related auto_complete field. So that the selected record is shown a bit wider.

<span class="select2 select2-container select2-container--admin-autocomplete select2-container--focus" dir="ltr" style="width: 260px;">
 // ...
></span>

I created my own form and tried fiddling with widget.attrs (inside the init) but it has zero effect. Which itself is no strange, since these are all span elements rendered.

class OrderLineForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.fields['product'].widget.attrs.update({'stytle': 'width: 400px'})
        self.fields['product'].widget.attrs.update({'width': 400})

I was also looking which widget is being used, but didn't find it either. Djanog docs do explainThe form.Select is a simple dropdown list, which does not provide auto complete functionality.

I also tried changing some css for .select2 class, but seems to gave no effect.

1 Answers

Here is an example of how you can change size of both, selected and diplayed options on the autocomplete widget to fit the complete text size.

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

class OrderLineForm(forms.ModelForm):
        class Meta:
        model = YourModel
        fields = '__all__'

        widgets = {
            'product': AutocompleteSelect(
                YourModel._meta.get_field('product').remote_field,
                admin.site,
                attrs={'data-dropdown-auto-width': 'true', 'style': "width: 100%;"}
            ),
        }

Related