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>Since I love condition-less code, I use this solution. It's like in the django docs, but the ulgy <code>if __name__ == '__pain__'</code> gets avoided.</p>

<p>File with code:</p>

<pre><code># utils/do_good_stuff.py
# This file contains the code
# No `django.setup()` needed
# This code can be used by web apps and console scripts.

from otherlib import othermethod

def say_thank_you():
    ...
</code></pre>

<p>File for main:</p>

<pre><code># do_good_stuff_main.py
import django
django.setup()

def say_thank_you_main():
    from myapp import do_good_stuff
    return do_good_stuff()
</code></pre>

<p>setup.py:</p>

<pre><code>    'console_scripts': [
        'say_thank_you=myapp.do_good_stuff_main:say_thank_you_main',
    ...
</code></pre>

<p>This is my current solution. Ffeeback welcome. Is there something to improve?</p>

python django python-import hang