Login

Edit users on Group admin

Author:
cedriccollins
Posted:
June 2, 2011
Language:
Python
Version:
1.2
Score:
0 (after 0 ratings)

Ordinarily, it is not possible to edit Group membership from the Group admin because the m2m relationship is defined on User. With a custom form, it is possible to add a ModelMultipleChoiceField for this purpose. The trick is to populate the initial value for the form field and save the form data properly.

One of the gotchas I found was that the admin framework saves ModelForms with commit=False and uses the save_m2m method when the group is finally saved. In order to preserve this functionality, I wrap the save_m2m method when commit=False.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from django import forms
from django.contrib import admin
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.contrib.auth.admin import GroupAdmin
from django.contrib.auth.models import Group

class GroupAdminForm(forms.ModelForm):
    users = forms.ModelMultipleChoiceField(queryset=AGLUser.objects.all(),
                                           widget=FilteredSelectMultiple('Users', False),
                                           required=False)
    class Meta:
        model = Group
        
    def __init__(self, *args, **kwargs):
        instance = kwargs.get('instance', None)
        if instance is not None:
            initial = kwargs.get('initial', {})
            initial['users'] = instance.user_set.all()
            kwargs['initial'] = initial
        super(GroupChangeForm, self).__init__(*args, **kwargs)
        
    def save(self, commit=True):
        group = super(GroupChangeForm, self).save(commit=commit)
        
        if commit:
            group.user_set = self.cleaned_data['users']
        else:
            old_save_m2m = self.save_m2m
            def new_save_m2m():
                old_save_m2m()
                group.user_set = self.cleaned_data['users']
            self.save_m2m = new_save_m2m
        return group

class MyGroupAdmin(GroupAdmin):
    form = GroupAdminForm

site = admin.AdminSite()
site.register(Group, MyGroupAdmin)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

gwikle (on December 9, 2014):

I believe there are a couple typos:

  1. AGLUser -> User and User would have to be imported. So add: from django.contrib.auth.models import User
  2. GroupChangeForm -> GroupAdminForm

Once you make these changes the form works great.

#

Please login first before commenting.