Reputation: 443
I want to create two groups once per project's life. So, I read about AppConfig
And I created core.appconfig.py
:
from django.apps import AppConfig
from django.contrib.auth.models import Group
class RolesConfig(AppConfig):
name = 'roles_config'
verbose_name = 'Roles configuration'
def create_roles(self):
driver = Group.objects.create(name='driver')
manager = Group.objects.create(name='manager')
driver.save()
manager.save()
And the in settings.py
: default_app_config = 'core.appconfig.RolesConfig'
But when I run server and go to the admin page, there are no groups. Why? When is AppConfig
called?
Upvotes: 0
Views: 124
Reputation: 53699
Consider using a data migration:
manage.py makemigrations <app_name> --empty
.def create_roles(apps, schema_editor):
Group = apps.get_model('auth', 'Group')
driver = Group.objects.create(name='driver')
manager = Group.objects.create(name='manager')
RunPython
operation to you migrations:class Migration(migrations.Migration):
operations = [
migrations.RunPython(create_roles),
]
Automatic loading of data fixtures has been deprecated in favour of data migrations.
Upvotes: 4
Reputation: 6488
There are several things wrong here:
Make sure the path to appconfig.py
is myapp/appconfig.py
.
Make sure that name
is your Django application name (e.g. myapp
).
Rename create_roles(self)
to ready(self)
.
In myapp/__init__.py
(create this file if it doesn't exist) add this line:
default_app_config = 'myapp.appconfig.RolesConfig'
Remove driver.save()
and manager.save()
, they are redundant because create()
already does save the objects in the database.
(Replace myapp
with your Django application name.)
Upvotes: 1
Reputation: 2263
I consider @Leistungsabfall answer to be correct, apart from that: don't do this. App config was not built for this purpose, instead you should create fixtures: https://docs.djangoproject.com/en/1.8/howto/initial-data/ .
App config is run every time you run the application so it would not really work.
Upvotes: 3