What is purpose of django.setup()?

Viewed 1793

I am updating website of my previous employee & have some issue with following code.

What is purpose of django.setup() line in following code. Is it necessary to put below code in init.py file.

from __future__ import absolute_import, unicode_literals
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sparrow.settings")
django.setup()
1 Answers

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.

As mentioned in the docs, django.setup() may only be called once. So, if you are facing an issue with the code, you could try modify the code into this:

from __future__ import absolute_import, unicode_literals
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app_name.settings")
if __name__ == '__main__':
   django.setup()
Related