How to approve all installed apps permission programmatically in Django

Viewed 270

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',

    # Local apps
    'users.apps.UsersConfig',

    # Third party apps
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
]

views.py


@user_passes_test(lambda u: u.is_superuser)
def create_group(request):
    groups = Group.objects.all()
    if request.method == 'POST':
        group_name = request.POST.get('group_name')
        group = Group.objects.create(name=group_name)
        return HttpResponse(group.name)
    else:
        ctx = {'groups': groups}
        return render(request, 'users/admin/create_group.html', ctx)

Here, I've created a view for creating user group programmatically. Now I want to allow users to approve permission just like django-admin dashboard. Like select few permissions and then press submit button to add these permissions to selected group. There must be some way doing so, because django admin itself doing it this way. I'd like to get some ideas how can I get this done.

1 Answers

Django implements this itself with a ManyToManyField between Group and Permission. The Permission object makes use of a content_type field to refer to the ContentType model [Django-doc] that specifies all models.

If you thus want to add a permission with a given codename to a Group, you can use:

from django.contrib.auth.models import Permission

permission = Permission.odocumentenbjects.get(codename='add_mymodel')

mygroup.permissions.add(permission)

Or if you for example want to add all permissions for a given model Foo, you can use:

from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType

permissions = Permission.objects.filter(
    content_type=ContentType.objects.get_for_model(Foo)
)

mygroup.permissions.add(*permissions)

You can also create extra permissions just like you create objects for another model and add these to group of course.

You can also add all permissions with:

from django.contrib.auth.models import Permission

permissions = Permission.objects.all()

mygroup.permissions.add(*permissions)
Related