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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s