Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Admin change widget type

I want to change the widget type of my many2many relationship to "FilteredSelectMultiple"

I learned from other questions and the documentation that this should do the trick

admin.py
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.db import models
from django import forms

class MyModelAdmin(admin.ModelAdmin):
    formfield_overrides = {
            forms.ModelMultipleChoiceField: {'widget': FilteredSelectMultiple},
    }

Unfortunatly nothing changes in the admin pages. Can anybody help?

like image 440
caliph Avatar asked Dec 10 '22 19:12

caliph


1 Answers

Your formfield_overrides isn't having any effect because you should use the model field, i.e. models.ManyToManyField instead of the form field, forms.MultipleChoiceField. However, simply switching the key to models.ManyToManyField won't work, because the widget should be instantiated with the field name and a boolean is_stacked.

There are a couple of other approaches:

To use a FilteredSelectMultiple for individual fields, use the filter_horizonal or filter_vertical options.

class MyModelAdmin(admin.ModelAdmin):
    filter_horizontal = ('my_m2m_field',)

To override the widget for all many to many fields, you could override formfield_for_manytomany.

from django.contrib.admin import widgets

class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_manytomany(self, db_field, request, **kwargs):
        vertical = False  # change to True if you prefer boxes to be stacked vertically
        kwargs['widget'] = widgets.FilteredSelectMultiple(
            db_field.verbose_name,
            vertical,
        )
        return super(MyModelAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)

Don't forget to register your model with your model admin.

admin.site.register(MyModel, MyModelAdmin)
like image 169
Alasdair Avatar answered Jan 29 '23 07:01

Alasdair