Django Modelform with Many-to-Many

Django (1.5) Modelform is supposed to handle many-to-many fields. In my case, I was editing the Django User model with Django groups. Everything seemed to be working correctly. The correct group associations were automatically showing up in the many-to-many widget. The problem was the new associations were not being saved.

A quick look at the docs revealed a discussion of the problems that can happen with many-to-many when a save is done using commit=False. But I was not doing that.

Turns out the problem was in my multi-select widget. I am using the “Whitelabel” theme from auto-magically replaces clunky widgets with better widgets. When I used a bare-bones HTML template, the many-to-many worked.

When I looked at the cleaned data right before the save command, I noticed that the Groups query set was empty. Adding the following to the form’s clean methods solved the problem:

def clean_groups(self):
    if 'groups[]' in
        group_ids = [int(x) for x in['groups[]']]
        g = Group.objects.filter(id__in=group_ids)
        g = Group.objects.none()
    return g