Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing code on startup in Django 1.7

Tags:

python

django

It seems Django allows to execute the code on startup - when the app starts, however, it's not clear and where I should put the code. So how can I execute the code on startup in Django 1.7?

like image 671
Incerteza Avatar asked Mar 06 '15 10:03

Incerteza


People also ask

How do I run code when Django starts?

Basically, you can use <project>/wsgi.py to do that, and it will be run only once, when the server starts, but not when you run commands or import a particular module. Again adding a comment to confirm that this method will execute the code only once.

Which file runs first in Django?

The First line will create a migration file by Django which are basically commands on how to convert the model into a database table. The Second line will execute the commands and creates a table called User with the given attributes and conditions.

What is AppConfig Django?

The AppConfig class used to configure the application has a path class attribute, which is the absolute directory path Django will use as the single base path for the application.


1 Answers

For Django>=1.7 you can use the AppConfig.ready() callback:

https://docs.djangoproject.com/en/dev/ref/applications/#django.apps.AppConfig.ready

For previous versions, see this answer.

If you are using the AppConfig.ready() method:

1) Create a myapp/apps.py module and subclass the AppConfig. For example:

from django.apps import AppConfig

class MyAppConfig(AppConfig):
    name = 'myapp'
    def ready(self):
    ...

2) Edit myapp/__init__.py and register your app config:

default_app_config = 'myapp.apps.MyAppConfig'

See https://docs.djangoproject.com/en/1.7/ref/applications/#configuring-applications for details.

like image 174
Selcuk Avatar answered Oct 29 '22 14:10

Selcuk