Django 1.7 where to put the code to add Groups programmatically?

前端 未结 2 861
独厮守ぢ
独厮守ぢ 2021-02-02 14:33

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 ad

2条回答
  •  北海茫月
    2021-02-02 14:43

    I was recommended this way to do it:

    Create a fake migration in the appropriate module:

    python manage.py makemigrations --empty yourappname
    

    Open up the file that was created, which should look like this:

    # -*- coding: utf-8 -*-
    from django.db import models, migrations
    
    class Migration(migrations.Migration):
    
        dependencies = [
            ('yourappname', '0001_initial'),
        ]
    
        operations = [
        ]
    

    And add your code:

    # -*- coding: utf-8 -*-
    from django.db import models, migrations
    
    def add_group_permissions():
        #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')
    
    class Migration(migrations.Migration):
    
        dependencies = [
            ('yourappname', '0001_initial'),
        ]
    
        operations = [
            migrations.RunPython(add_group_permissions),
        ]
    

    Finally, run the migration:

    python manage.py migrate
    

    This is nice because you can deploy to Heroku or wherever and be sure it'll be applied, as it's just another migration.

提交回复
热议问题