Login

Group permissions selection in admin filtered by your app models

Author:
estecb
Posted:
February 4, 2014
Language:
Python
Version:
1.6
Score:
1 (after 1 ratings)

Sometimes you just don't want to display every permission django has, you just want a short list showing the permissions for some of your apps (or even django core apps).

GROUP_PERMISSIONS_MODELS must be a list of your app models. Dotted path (in lowercase) required, app name + model class name.

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

Comments

Please login first before commenting.