how to resize django ManyToManyField widget on admin page

You can resize the widget by overriding CSS styles.

You'll need to override the following CSS classes:

  1. .selector - this div contains both the widgets.

  2. .selctor-available - this div contains the widget on the left.

  3. .selector-chosen - this div contains the widget on the right.

First, create a CSS file called resize-widget.css inside your project's static directory. Add the following code to the file:

UPDATE: For Django v2, these CSS rules will not work. See the other answer posted below.

.selector-available,
.selector-chosen {
    width: 200px;
}

.selector .selector-available input {
    width: 184px;
}

.selector select {
    width: 200px;
}

.selector {
    width: 450px;
}

In admin.py, supply that CSS file via class Media:

@admin.register(Pen)
class PenAdmin(admin.ModelAdmin):
    filter_horizontal = ('materials',)

    class Media:
        css = {
            'all': ('resize-widget.css',), # if you have saved this file in `static/css/` then the path must look like `('css/resize-widget.css',)`
        }

Visit admin site. The select widget must look like this:

enter image description here


I tried xyres answer and found that it worked BUT some of the CSS rules were being overridden by other rules that used more specific selectors.

To fix this I modified resize-widget.css to the following:

.form-horizontal .control-group .controls .selector {
    width: 100%;
}

.form-horizontal .control-group .controls .selector .selector-available,
.form-horizontal .control-group .controls .selector .selector-chosen {
    max-width: 45%;
}

.form-horizontal .control-group .controls .selector select {
    min-height: 200px;
}

These more specific rules were not being overridden and made it work for me.

Tags:

Django

Admin