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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With