Search code examples
pythondjangoreusabilitydjango-tinymce

how a django reusable apps can initialize itself?


I'm creating a django app as a python package , almost similar to django-tinymce
interesting point about django-tinymce is that every time I restart my web server , for example I run :

python manage.py runserver

somehow automatically a settings.py file inside django-tinymce start running.
how is this possible ?
I just add tinymce in the INSTALLED_APPS and nothing else but the code inside python2.7/site-packages/tinymce/settings.py starts running and do a few initialization operations every time I restart my web server or run any manage.py command.


Solution

  • As django 1.7 each app can contain an app.py file to do any initialization it needs to do. Imagine we have a app called profile.In your app directory create an apps.py like this :

    #apps.py 
    from django.apps import AppConfig 
    class ProfileConfig(AppConfig):
         name = "profiles"
         verbose_name = 'User Profiles'
         def ready(self):
             #do what ever you want
    

    One more step to complete this behavior is to specify default_app_config Which should happened in init.py of your app :

    # profile/__init__.py
    default_app_config = 'profile.apps.ProfileConfig'
    

    This behavior can be used in many usecases including : changing project settings,registering signal handlers

    More details can be found in Django 1.7 release notes and Django docs:Applications