Edit users on Group admin

 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. Lazy options on ModelForm fields - like setting a ModelChoiceField queryset from the view by jpic 4 years, 5 months ago
  2. newforms-admin edit callback-url hook by myers 5 years, 2 months ago
  3. Complex Formsets, Redux by smagala 3 years, 3 months ago
  4. ManyToManyField no syncdb by powerfox 4 years, 4 months ago
  5. group_required decorator by msanders 3 years, 9 months ago

Comments

arcanosam (on January 4, 2012):

thanks for sharing this snippet. works perfectly. I just need to fix this (using django 1.2.7):

line 8: AGLUser -> User

line 20: GroupChangeForm -> GroupAdminForm

line 23: GroupChangeForm -> GroupAdminForm

For using that snippet, I copy this class and append (on the EOF) to that other snippet:

http://djangosnippets.org/snippets/876/

and include this line:

GroupAdmin.form = GroupAdminForm

flawlessly :D

thanks again

#

(Forgotten your password?)