How I can use python in order to populate and modify groups?
I am using proxy models in order to manage Users and groups?
class User(AbstractUser):
bio = models.TextField()
def __str__(self):
return self.first_name+' '+self.last_name
class Author(Group):
class Meta:
proxy=True
permissions=[("create_article","User can create article"),("edit_article","Edit Article")]
class Publisher(Group):
class Meta:
proxy=True
permissions=[("edit_article","Edit Article")]
Is there a way to automatically create the nessesary migration in order once I change the permissions upon code also be changed into Db as well?
My goal is somehow to have a config file with all permissions and a list that would define what permissions each groups would have. Then using this config file the django would check the user permissions.
You don't need proxy models for this.
Django already has a built-in relationship between Group and Permission. Define your permissions on the model, then assign them to groups.
class Article(models.Model):
class Meta:
permissions = [
("create_article", "Can create article"),
("edit_article", "Can edit article"),
]
Then create a small management command to keep your group configuration synchronized:
GROUP_PERMISSIONS = {
"Author": ["create_article", "edit_article"],
"Publisher": ["edit_article"],
}
Your command can then do:
group.permissions.set(
Permission.objects.filter(codename__in=permission_codes)
)
Run it after migrations:
python manage.py migrate
python manage.py sync_permissions
This is preferable to trying to make makemigrations track permission assignments.
makemigrations is primarily for schema changes. Group/permission assignments are database data, so a management command or data migration is a better fit.
And in your application, you can simply check:
request.user.has_perm("your_app.edit_article")
If the permissions are meant to be configurable by admins at runtime, don't keep them in a config file at all. Let Django's Group/Permission tables be the source of truth.