Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to programmatically create custom Django permissions?

The permission/authentication documentation for Django 1.4 provides the following snippet for creating custom permissions programmatically:

Edit: (I would like to employ this for permissions that are not necessarily linked to a specific model class, but more general permissions that span multiple types.)

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

content_type = ContentType.objects.get(app_label='myapp', model='BlogPost')
permission = Permission.objects.create(codename='can_publish',
                                       name='Can Publish Posts',
                                       content_type=content_type)

Source

My question is where this code should be placed. Obviously these should only be created once, but I don't want to have to do it in the shell. It seems like this should be stored in a file somewhere. (For documentation sake.)

like image 971
Craig Otis Avatar asked Apr 08 '12 14:04

Craig Otis


People also ask

What is Auth_user_model in Django?

Django allows you to override the default user model by providing a value for the AUTH_USER_MODEL setting that references a custom model. Method 2 – AUTH_USER_MODEL : AUTH_USER_MODEL is the recommended approach when referring to a user model in a models.py file.

How do I add custom permissions to Django?

Django Admin Panel : In Admin Panel you will see Group in bold letter, Click on that and make 3-different group named level0, level1, level3 . Also, define the custom permissions according to the need. By Programmatically creating a group with permissions: Open python shell using python manage.py shell.

How does Django permissions work?

By default, Django automatically gives add, change, and delete permissions to all models, which allow users with the permissions to perform the associated actions via the admin site. You can define your own permissions to models and grant them to specific users.


1 Answers

Usually it is enough to just add the needed permissions to the corresponding model class using the permissions meta attribute.

This is from the official documentation:

class Task(models.Model):
    ...
    class Meta:
        permissions = (
            ("view_task", "Can see available tasks"),
            ("change_task_status", "Can change the status of tasks"),
            ("close_task", "Can remove a task by setting its status as closed"),
        )
like image 185
Arseny Avatar answered Sep 22 '22 18:09

Arseny