How to call django.setup() in console_script?
<p>The current django docs tell me this:</p>

<blockquote>
  <p>django.setup() may only be called once.</p>
  
  <p>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:</p>
</blockquote>

<pre><code>if __name__ == '__main__':
    import django
    django.setup()
</code></pre>

<p>Source: <a href="https://docs.djangoproject.com/en/1.10/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage">Calling django.setup() is required for âstandaloneâ Django usage</a></p>

<p>I am using entry points in setup.py. This way I don't have <code>__name__ == '__main__'</code>.</p>

<h1>Question</h1>

<p>How to ensure django.setup() gets only called once if you use <a href="http://python-packaging.readthedocs.io/en/latest/command-line-scripts.html#the-console-scripts-entry-point">console_scripts</a>?</p>

<p>Where should I put <code>django.setup()</code>?</p>

<h1>Background</h1>

<p>The actual error I have: Django hangs. Here is the reason: <a href="https://code.djangoproject.com/ticket/27176">https://code.djangoproject.com/ticket/27176</a></p>

<p>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.</p>

<p>Here <a href="https://docs.djangoproject.com/en/1.10/_modules/django/#setup" rel="nofollow">https://docs.djangoproject.com/en/1.10/_modules/django/#setup</a> we can see what <code>django.setup</code> actually does.  </p>

<blockquote>
  <p>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 <code>set_prefix</code> is True.</p>
</blockquote>

<p>So basically to ensure that setup was already done we can check if apps are ready and settings are configured</p>

<pre><code>from django.apps import apps
from django.conf impor settings

if not apps.ready and not settings.configured:
    django.setup()
</code></pre>

python django python-import hang