Login

Edit users on Group admin

Author:
cedriccollins
Posted:
June 2, 2011
Language:
Python
Version:
1.2
Tags:
admin
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. newforms-admin edit callback-url hook by myers 7 years, 2 months ago
  2. Support for permissions for anonymous users in django ModelBackend by jb 3 years, 8 months ago
  3. Admin page without inlines dinamically by davmuz 3 years ago
  4. Re-editable FormPreview by hdknr 5 years, 2 months ago
  5. Improved Pickled Object Field by taavi223 5 years, 10 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.