How to run a function at startup before requests are handled in Django?

I want to run some code when my Django server starts-up in order to clean up from the previous end of the server. How can I run some code once and only once at startup before the server processes any requests. I need to access the database during this time.

I've read a couple of things online that seem a bit outdated and are also not guaranteed to run only once.

This is often done with the .ready() method [Django-doc] of any of the AppConfig classes [Django-doc] of an installed app. So if you have an app named app_name, you can work with:

# app_name/apps.py

from django.apps import AppConfig


class MyAppConfig(AppConfig):
    # …

    def ready(self):
        # my management command
        # …

This will run after the models of all INSTALLED_APPS are loaded, so you can do management commands. This is also often used to hook signals to models.

Back to Top