When are user permissions ready? - trying to assign permission in post-migration signal
Fairly new to django so there must be a lot I have no idea about.
How can I assign user related permissions to user groups in a post migration signal?
I have read everywhere that post migration signal can work which actually does... to an extent. I can create the required user groups and assign permissions to them but the ones related to user model. E.g. view_user, create_user, change_user are not ready to be assigned in post migration.
Im not sure of all the options I have here but already tried to define a migration file and nitpicking sender does not look like a way forward either.
Signal handler:
@receiver(post_migrate)
def create_groups_and_assign_permissions(sender, **kwargs):
print(f"sender: {sender}")
# Only run after auth migrations
if sender.label != "auth":
return
for (code_name, name), permission_codenames in GROUPS_AND_PERMISSIONS.items():
group, _ = Group.objects.get_or_create(name=name)
GroupMetadata.objects.get_or_create(
group=group, code_name=code_name, display_name=name
)
for codename in permission_codenames:
try:
perm = Permission.objects.get(codename=codename)
group.permissions.add(perm)
except Permission.DoesNotExist:
print(f"[WARNING] Permission '{codename}' does not exist yet")
Singal is imported in the AppConfig:
from django.apps import AppConfig
class UserGroupsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "apps.users.features.user_groups"
def ready(self):
# Register signals
import apps.users.features.user_groups.signals # pylint: disable=unused-import, import-outside-toplevel
GROUPS_AND_PERMISSIONS constants:
GROUPS_AND_PERMISSIONS = {
("manager", "Manager"): [
...
"add_profile",
"change_profile",
"view_profile",
"add_user",
"change_user",
"view_user",
"view_groupmetadata",
"view_group",
...
],
... other roles ...
Output:
Running migrations:
No migrations to apply.
sender: <AdminConfig: admin>
sender: <AuthConfig: auth>
[WARNING] Permission 'add_user' does not exist yet
[WARNING] Permission 'change_user' does not exist yet
[WARNING] Permission 'view_user' does not exist yet
sender: <ContentTypesConfig: contenttypes>
sender: <SessionsConfig: sessions>
sender: <UsersConfig: users>
sender: <ProfilesConfig: profiles>
sender: <UserGroupsConfig: user_groups>
sender: <StoragesConfig: storages>
sender: <PdfExportsConfig: pdf_exports>
...