I\'m writing a Django Middleware class that I want to execute only once at startup, to initialise some other arbritary code. I\'ve followed the very nice solution posted by
As suggested by @Pykler, in Django 1.7+ you should use the hook explained in his answer, but if you want that your function is called only when run server is called (and not when making migrations, migrate, shell, etc. are called), and you want to avoid AppRegistryNotReady exceptions you have to do as follows:
file: myapp/apps.py
import sys
from django.apps import AppConfig
class MyAppConfig(AppConfig):
name = 'my_app'
def ready(self):
if 'runserver' not in sys.argv:
return True
# you must import your modules here
# to avoid AppRegistryNotReady exception
from .models import MyModel
# startup code here