DmitryRus
DmitryRus

Reputation: 101

How in Django admin create Groups with permissions for models programmatically?

I want to create two groups "Driver" and "Administrator". Each group should be have deference permissions for models.

"Administrator" able to add, delete and view certain models.

"Driver" able to just add and view certain models.

What is the best approach to make this done?

Upvotes: 2

Views: 884

Answers (1)

Fomalhaut
Fomalhaut

Reputation: 9785

It depends on the action in your project that leads to create these groups. I can guess, you want to create these groups once when you deploy your project without the need to enter the admin panel and create the groups manually. If so, I would recommend you to try RunPython migration for it: https://docs.djangoproject.com/en/3.0/ref/migration-operations/#django.db.migrations.operations.RunPython

Also you will need to work with the model Group: https://docs.djangoproject.com/en/3.0/ref/contrib/auth/

A quick example of the migration would look like this:

from django.db import migrations


def forwards_func(apps, schema_editor):
    Group = apps.get_model("django.contrib.auth", "Group")
    # Create the groups you need here...


def reverse_func(apps, schema_editor):
    Group = apps.get_model("django.contrib.auth", "Group")
    # Delete the groups you need here...


class Migration(migrations.Migration):

    dependencies = []

    operations = [
        migrations.RunPython(forwards_func, reverse_func),
    ]

Creating a new empty migration is available by the command:

python manage.py makemigrations myapp --empty

Upvotes: 1

Related Questions