Python Answers

How to execute code when Python Django starts once only?

Spread the love

To execute code when Python Django starts once only, we can put our code in the AppConfig class.

For instance, we write

from django.apps import AppConfig

class MyAppConfig(AppConfig):
    name = 'myapp'
    verbose_name = "My Application"
    def ready(self):
        pass # startup code here

to create the MyAppConfig that inherits from the AppConfig class.

And we put our startup code in the ready method.

Then in myapp/, we add

default_app_config = 'myapp.apps.MyAppConfig'

to set the default_app_config to the path to our MyAppConfig class in our app to make Django run it on startup.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *