I have been trying to find the answer in the Django Auth docs, but can not seem to find what I am looking for.
The problem I am having is, when I define the code for adding Groups (same as Groups in the admin page):
#read_only
group, created = Group.objects.get_or_create(name='read_only')
if created:
group.permissions.add(can_read_campaign)
logger.info('read_only_user Group created')
#standard
group, created = Group.objects.get_or_create(name='standard_user')
if created:
group.permissions.add(can_edit_users)
logger.info('standard_user Group created')
#admin
group, created = Group.objects.get_or_create(name='admin_user')
if created:
group.permissions.add(can_edit_campaign, can_edit_users)
logger.info('admin_user Group created')
When I have run this code in models.py and init.py and they both give me this error:
django.core.exceptions.AppRegistryNotReady
I presume this is due to the Model/init trying to insert things into the django app/admin too early?
How can I add these Groups programmatically?
EDIT:
This is not a duplicate question, this was actually adding permission and groups within the models during setup of the project, rather than through the shell.
I have solved this issues, by using signals and receivers (django modules).
I added the code to create the permissions/groups into it's own function and decorated this with a receiver (post_migrate), which will run this function after migrations are complete, removing this error.
@receiver(post_migrate)
def init_groups(sender, **kwargs):
#permission and group code goes here
Combining @Robert Grant and this I was able to do it like:
And then:
Note: this works on Django 3.x, but I'm pretty sure it will work for Django 1.7 as well.
I was recommended this way to do it:
Create a fake migration in the appropriate module:
Open up the file that was created, which should look like this:
And add your code:
Finally, run the migration:
This is nice because you can deploy to Heroku or wherever and be sure it'll be applied, as it's just another migration.