Nirmal Mulji
Nirmal Mulji

Reputation: 25

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

Upvotes: 0

Views: 2593

Answers (1)

Gasanov
Gasanov

Reputation: 3399

You have incorrect syntax in register method:

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

Upvotes: 5

Related Questions