Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import Django Settings to python standalone script

I'm having difficulty calling a django script. Here is what I'm currently doing in my root directory:

>>> import os
>>> os.environ['DJANGO_SETTINGS_MODULE'] = 'settings.py'
>>> from django.conf import settings
>>> settings.configure()
>>> settings.DATABASES
{}

The settings.DATABASES should not be empty, so I know I haven't initialized the project correct. How would I do this in django2.1? I used to be able to do this easily using import settings; setup_environ(settings), but not anymore.

Note: I'm looking to be able to run the above from any directory. Here is an example from trying to import my project from tmp:

(V) david$ cd /tmp && python

>>> import django
>>> from django.conf import settings
>>> settings.configure()
>>> django.setup()
>>> from users.models import *
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'users'

1 Answers

The 2.1 docs state that you need to use setup() now. Relevant snippet:

import django
from django.conf import settings

settings.configure()
django.setup()

# Now this script or any imported module can use any part of Django it needs.
from myapp import models

Here is the full documentation.

like image 154
Julian Avatar answered Oct 25 '25 05:10

Julian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!