I have a python script test.py that imports make_password function from Django library. It does it like this:
from django.contrib.auth.hashers import make_password
.... a lot of other stuff
def init():
...
if __name__ == "__main__":
init()
So, I want to run it from the command line like:
python test.py
But this results in a whole list of error messages, which are all about importing Django module. If I comment out from django.contrib.auth.hashers import make_password, then everything is ok (except the fact that I can't use make_password function).
1 Answer 1
The error messages your are getting are most likely complaints that the settings module is not available.
Django initializes its runtime environment (via django.core.management.setup_environ()) when you import any of its core modules. The django ecosystem is not meant to function without a valid project environment.
You have at least two options:
1. Manually set django settings module
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'yourapp.settings'
from django.contrib.auth.hashers import make_password
...
Note that this requires yourapp.settings to be available via sys.path, so it might be necessary to explicitly add the project path to sys.path (or PYTHON_PATH).
Other versions of basically the same thing are available.
2. Build a management command
This is explained in some detail in the documentation.
In principle, you need to provide a yourapp.management.mycommand module that contains a single Command class:
class Command(BaseCommand):
def handle(self, *args, **options):
# make_password()
The command can be run through django's manage.py.
3 Comments
yourapp.settings. I have a project proj1 and I have an application called accent (they are in the same folder). So, how should I specify yourapp.settings? Should it be proj1.settings or accent.settings or should I use the full path to the application (or the project?)proj1.settings and accent.settings - I get an error No module name proj1.settings or No module named accent.settings, respectively. So, there should be some magic with how to set 'DJANGO_SETTINGS_MODULE'proj1.settings. Also, the project module needs to be available via Python's module path. You might need to add the project's root directory to sys.path (or PYTHON_PATH) if the script is not at the root of the project directory.