Andrew
Andrew

Reputation: 443

Do something once in django

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

Answers (3)

knbk
knbk

Reputation: 53699

Consider using a data migration:

  1. Create an empty migration file with manage.py makemigrations <app_name> --empty.
  2. Create a function that adds the default values to the database.
def create_roles(apps, schema_editor):
    Group = apps.get_model('auth', 'Group')
    driver = Group.objects.create(name='driver')
    manager = Group.objects.create(name='manager')
  1. Add a 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

Leistungsabfall
Leistungsabfall

Reputation: 6488

There are several things wrong here:

  1. Make sure the path to appconfig.py is myapp/appconfig.py.

  2. Make sure that name is your Django application name (e.g. myapp).

  3. Rename create_roles(self) to ready(self).

  4. In myapp/__init__.py (create this file if it doesn't exist) add this line:

    default_app_config = 'myapp.appconfig.RolesConfig'
    
  5. 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

Visgean Skeloru
Visgean Skeloru

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

Related Questions