0

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

1 Answers1

5

You have incorrect syntax in register method:

class HotelAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.ManyToManyField: {'widget': CheckboxSelectMultiple},
    }
admin.site.register(Hotel, HotelAdmin)
Gasanov
  • 2,839
  • 1
  • 9
  • 21
  • is this also possible for one specific field (e.g. not all M2M fields)? e.g. in a custom user, I have a m2m to `plugins`- I want them as Checkboxes, but not `groups` - those are many. – nerdoc Jan 01 '23 at 15:08
  • @nerdoc you will need to create custom form with different `Meta.widgets`. Refer to this answer https://stackoverflow.com/questions/4176613/django-admin-using-a-custom-widget-for-only-one-model-field – Gasanov Jan 02 '23 at 08:07
  • sure, this is possible, but e.g. complicated for e.g. an extended UserAdmin that just needs another field of a custom user which is a M2M... But I see, this is not possible. It would be so nice to tell Django: formfield_overrides = { "field_name": {'widget': CheckboxSelectMultiple}, } – nerdoc Jan 03 '23 at 14:40