The current django docs tell me this:
django.setup() may only be called once.
Therefore, avoid putting reusable application logic in standalone scripts so that you have to import from the script elsewhere in your application. If you can’t avoid that, put the call to django.setup() inside an if block:
if __name__ == '__main__':
import django
django.setup()
Source: Calling django.setup() is required for “standalone” Django usage
I am using entry points in setup.py. This way I don't have __name__ == '__main__'
.
How to ensure django.setup() gets only called once if you use console_scripts?
Where should I put django.setup()
?
The actual error I have: Django hangs. Here is the reason: https://code.djangoproject.com/ticket/27176
I want to port my application to the current django version. Changing to a management command is not an option, since other (third party applications) rely on the existence of my console scripts.
It is used if you run your Django app as standalone. It will load your settings and populate Django's application registry. You can read the detail on the Django documentation.
When you use Django, you have to tell it which settings you're using. Do this by using an environment variable, DJANGO_SETTINGS_MODULE . The value of DJANGO_SETTINGS_MODULE should be in Python path syntax, e.g. mysite. settings .
Here https://docs.djangoproject.com/en/1.10/_modules/django/#setup we can see what django.setup
actually does.
Configure the settings (this happens as a side effect of accessing the first setting), configure logging and populate the app registry. Set the thread-local urlresolvers script prefix if
set_prefix
is True.
So basically to ensure that setup was already done we can check if apps are ready and settings are configured
from django.apps import apps
from django.conf import settings
if not apps.ready and not settings.configured:
django.setup()
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