Group permissions selection in admin filtered by your app models

 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#admin.py, you may create a new app, or put it in your "admin" app if you happen to have one.

from django.contrib import admin
from django.contrib.admin import widgets
from django.utils.translation import ugettext_lazy as _
from django import forms
from django.contrib.auth.models import Permission, Group
from django.db.models import Q
from django.conf import settings


def get_permissions():
    app_models_dict = {}

    for app_model in settings.GROUP_PERMISSIONS_MODELS:
        app, model = app_model.split(".")
        app_models_dict.setdefault(app, []).append(model)

    q = Q()

    for app, models in app_models_dict.iteritems():
        q |= Q(content_type__app_label=app, content_type__model__in=models)

    if q:
        return Permission.objects.filter(q)
    else:
        return Permission.objects.all()


class GroupAdminForm(forms.ModelForm):

    permissions = forms.ModelMultipleChoiceField(
        queryset=get_permissions(),
        widget=widgets.FilteredSelectMultiple(_('permissions'), False))

    class Meta:
        model = Group


class GroupAdmin(admin.ModelAdmin):

    form = GroupAdminForm
    search_fields = ('name', )
    ordering = ('name', )


admin.site.unregister(Group)
admin.site.register(Group, GroupAdmin)


# settings.py

GROUP_PERMISSIONS_MODELS = ['app1.modelname', 'app2.modelname', ]

More like this

  1. More information about users and groups in user admin by ramusus 4 years, 8 months ago
  2. More information about users and groups in user admin by buriy 5 years, 9 months ago
  3. Row-Level, URL-based permissions for FlatPages by bradmontgomery 4 years, 10 months ago
  4. Create permissions for proxy models by charettes 2 years, 2 months ago
  5. AdminPeepingMiddleware by buriy 6 years, 7 months ago

Comments

(Forgotten your password?)