Search code examples
pythondjangodjango-adminmany-to-manydjango-widget

Django admin CheckboxSelectMultiple widget not working for ManyToManyField


I'm using the below model where the default django users table has a many-to-many relationship with Hotel's.

Assigning multiple users to a Hotel in the django admin panel is difficult, and I want to replace the default 'ctrl-click' method to a checkbox where I can select multiple users without having to hold down ctrl.

Model:

from django.db import models
from django.contrib.auth.models import User

class Hotel(models.Model):
    # associate the user
    user = models.ManyToManyField(User)
    # additional fields
    hotel_name = models.CharField(max_length=100)
    hotel_id = models.CharField(max_length=100)

    def __str__(self):
        return self.hotel_id

admin.py

from django.contrib import admin
from .models import *
from django.forms import CheckboxSelectMultiple


# Checkbox for many-to-many fields
class HotelAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.ManyToManyField: {'widget': CheckboxSelectMultiple},
    }

admin.site.register(Hotel)

result: The formfield_override does not work, and selecting users to a hotel is not a checkbox enter image description here


Solution

  • You have incorrect syntax in register method:

    class HotelAdmin(admin.ModelAdmin):
        formfield_overrides = {
            models.ManyToManyField: {'widget': CheckboxSelectMultiple},
        }
    admin.site.register(Hotel, HotelAdmin)