[Django]-What gets executed as the server starts vs. as a request comes in?

6👍

You should never put code in settings.py that requires importing anything from any part of Django. Since many parts of Django require settings to be available, this is very likely to get you into circular import problems.

Your ROOT_URLCONF (urls.py) is a reasonable place to put project-level code that you want run once for each server Python process, before any requests are served.

If the code is specific to a particular app (and only needed if that app is in use) then you could put it in that app’s models.py or __init__.py.

For a broader look at the issue, see this blog post.

0👍

I’m not sure exactly what you mean by ‘class hacking’ but have you tried calling your changes from ./manage.py?

From the docs:

In addition, manage.py is
automatically created in each Django
project. manage.py is a thin wrapper
around django-admin.py that takes care
of two things for you before
delegating to django-admin.py:

It puts your project’s package on
sys.path. It sets the
DJANGO_SETTINGS_MODULE environment
variable so that it points to your
project’s settings.py file.

so if you have some stuff that you want to run after settings.py this might be the case if its a hack you’re after.

HTH

0👍

Something like the request_started signal?

👤oggy

-1👍

If you want to put code somewhere in your django project that will get run for certain every time you start up django, pick an app form INSTALLED_APPS. Both the __init__.py and the models.py will be run for sure. They are good places for things like signals or anything you must register.

👤defrex

Leave a comment