Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding Size of Django Admin Multi-select Widget

Newbie Django question: I'd like the Django admin to display more rows of choices in the multi-select widget. I have an extremely long list to select from and the default 4 rows just isn't convenient, especially when scrolling.

Right now, that widget is rendered as select multiple but I'd like it to be select multiple size="12". Ideally this should be for specific fields, but I can live with all fields rendering with the same size attribute.

So where would be the optimal place in Django to change that?

like image 709
Thomas Nashe Avatar asked Sep 08 '12 11:09

Thomas Nashe


People also ask

How do I override a Django form?

You can override forms for django's built-in admin by setting form attribute of ModelAdmin to your own form class. See: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form.

What is Attrs Django?

attrs . A dictionary containing HTML attributes to be set on the rendered DateInput and TimeInput widgets, respectively. If these attributes aren't set, Widget. attrs is used instead.

What is the significance of introducing custom widgets in Django?

The widget in Django will handle the rendering of the HTML elements and extract data from a POST/GET dictionary that corresponds to the same widget. Whenever we specify a field on a Django form, Django uses some default widget appropriate to the data type to be displayed.


1 Answers

I did this in the admin.py by setting a blanket size for all ManyToManyField items, for instance:

from django.contrib import admin
from django.forms import SelectMultiple
from django.db import models
from models import *

class RiverAdmin(admin.ModelAdmin):
    formfield_overrides = { models.ManyToManyField: {'widget': SelectMultiple(attrs={'size':'10'})}, }

admin.site.register(River, RiverAdmin)
like image 154
Jason Champion Avatar answered Sep 19 '22 09:09

Jason Champion