Access the Django database from a non-Django script

1

When I try to access the database that Django automatically creates from the interpreter, or from a script that Django has not created on its own, I receive an error.

Code where I try to import the User model of the application called app :

from app.models import User

Error that prints when trying to do that operation:

  

django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the variable environment DJANGO_SETTINGS_MODULE or call settings.configure () before accessing settings.

    
asked by ImHarvol 25.08.2017 в 18:24
source

1 answer

1

I put this snippet of code at the beginning of the script:

import os
import django
import sys
sys.path.append('../../')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "imharvol.settings")
django.setup()

But remember to change the directory in sys.path.append('../../') and put the base directory of your project (where is the manage.py). You will also have to change the imharvol os.environ.setdefault("DJANGO_SETTINGS_MODULE", "imharvol.settings") to the name of the directory where your settings.py file is, in this case, the project was called imharvol , and by default the settings are in a directory named just like the name of your project.

After this you can import your User model.

from app.models import User
    
answered by 25.08.2017 / 18:24
source