Home > Enterprise >  Add group and permission to group with migration django
Add group and permission to group with migration django

Time:09-14

i have problem with groups and permission in django. I want to create a group of users and admin. In django panel admin i see permission which i need:

  • app | user | Can add user
  • app | user | Can change user
  • app | user | Can delete user
  • app | user | Can view user

I need create group "user" and "admin" then add perm to user "Can view user" and to admin all this perms and this is need to do with migration.

My already code i suposed is totally stupid

# Generated by Django 4.0.3 on 2022-09-11 10:33

from django.db import migrations, transaction
from django.contrib.auth.models import Group, Permission


def add_group_permissions(a,b):
    group, created = Group.objects.get_or_create(name='user')
    try:
        with transaction.atomic():
            group.permissions.add(can_view_user)
            group.save()
    except InterruptedError:
        group.delete()


class Migration(migrations.Migration):
    dependencies = [
        ('app', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(add_group_permissions),
    ]

If anyone can help, i need that.

CodePudding user response:

I have some examples of custom permissions. In your models.py try this below your class:

class Meta:
        
        permissions = [
            ("access_app", "Can access the budget app"),  # access for all budget app
            (
                "level_2",
                "Can access the budget app - level 2",
            ),  # access to EyePlan model   hr
            (
                "level_3",
                "Can access the budget app - level 3",
            ),  # access to EyePlan model only
        ]

In your views.py:

class BudgetMixin(PermissionRequiredMixin):
    permission_required = "budget.access_app"

Try to customize this code for your own requirements, hope it gonna help you.

CodePudding user response:

Ok, i have that now in models.py:

from django.db import models
from django.contrib.auth.models import AbstractUser


class CustomUser(AbstractUser):
    username = models.EmailField(unique=True)
    name = models.CharField(max_length=64)
    last_name = models.CharField(max_length=64)
    phone_number = models.CharField(max_length=9, unique=True)
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = []

    class Meta:
        permissions = [
            ("can_add_user", "Can add user"),
            ("can_change_user", "Can change user"),
            ("can_delete_user", "Can delete user"),
            ("can_view_user", "Can view user"),
        ]

But how to create now group "user" wtih permission can_view_user and "admin" with: can_add_user; can_change_user; can_delete_user; can_view_user.

  • Related