0

I need to read a csv file just after running server. It can't be done in any view because it need to be preload to execute all views, so I need to do it immediately after "manage.py runserver". Is there any file where I can write the code that I need to execute in first place?

Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
Nelly Louis
  • 157
  • 2
  • 8
  • Possible duplicate of [Allow commands to run after backgrounding django runserver command in a bash script?](https://stackoverflow.com/questions/30237896/allow-commands-to-run-after-backgrounding-django-runserver-command-in-a-bash-scr) – SaeX May 01 '19 at 18:10
  • No because I can't type anything after "run server", that answer includes a command – Nelly Louis May 01 '19 at 18:14

2 Answers2

11

Code put in settings.py file may run when Django application as @salman-arshad suggested, but it is not the best way of doing it. It could be problematic or even dangerous according to the context of what you are running.

The first problem is code will run twice when the application starts. Django uses the settings.py file many times during startup and running. Just put print('Hello world') at the end of the settings.py file and you will see it printed twice. It means the code ran twice. Secondly, the settings.py file does not serve the purpose of running arbitrary code. It is dedicated to your project settings. Thirdly if you try to import anything from within the application in settings.py and use it (for instance a Model), it would cause errors. Because Django's internal app registry is not ready yet.

So the best place for running this type of code is in the ready hook of the AppConfig class. In any Django application, there is an apps.py file that defines a configuration class. You can override the ready function in it. This function will run only once when you start the application like this. Say you have an app named app_name

class AppNameConfig(AppConfig):
    name = 'app_name'

    def ready(self):
        pass
        # write your startup code here you can import application code here
        #from app_name.models import MyModel

then put the following line in that app's __init__.py file

default_app_config = 'app_name.apps.AppNameConfig'

Now, this code will run at every startup without problems.

Nafees Anwar
  • 6,324
  • 2
  • 23
  • 42
-1

Just add that script in settings.py file. Because settings.py file of those files which are executed prior to views.py file

Salman Arshad
  • 343
  • 6
  • 23