1

I am trying to make multiple user groups. Each groups has a set of seperate permissions. Is there a way to initialize a django project with user-group permissions from json. I am looking for methods like python manage.py loaddata user_groups.json.

Sudheer K
  • 1,244
  • 2
  • 18
  • 31

1 Answers1

1

You could create a Data Migration. It's basically a strategy where you create an empty migration file by running the command:

python manage.py makemigrations --empty yourappname

Then, inside this migration file you would write a Python script that adds the initial groups.

from django.db import migrations

def create_initial_groups(apps, schema_editor):
    Group = apps.get_model('auth', 'Group')
    # create initial groups...

class Migration(migrations.Migration):

    dependencies = [
        ('yourappname', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(create_initial_groups),
    ]

But, I don't know if this is such a good idea. Mainly because we don't have direct access to the auth app (which would be the correct place to create this migration file). So that means you would have to create this migration file inside one of your apps, and this could cause trouble, for example if Django tries to run this migration before migrating the auth models, so basically the Group model wouldn't exist. What I'm trying to say is that maybe you would have to migrate the apps separately to enforce the order (or maybe not).

The good thing about this strategy is because when someone starts the project and migrate the database, the initial data would be automatically applied via the migration, so it would be pretty much effortless for the person setting up your project.

Another option would be using loaddata to provide initial data for your models.

Vitor Freitas
  • 3,550
  • 1
  • 24
  • 35