django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TAB LESPACE, but settings are not configured
Question: I’m using Django 1.9.1 with Python 3.5.2 and I'm having a problem running a
Python script that uses Django models.

    
    
    C:\Users\admin\trailers>python load_from_api.py
    Traceback (most recent call last):
      File "load_from_api.py", line 6, in <module>
        from movies.models import Movie
      File "C:\Users\admin\trailers\movies\models.py", line 5, in <module>
        class Genre(models.Model):
      File "C:\Users\admin\trailers\movies\models.py", line 6, in Genre
        id = models.CharField(max_length=10, primary_key=True)
      File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\fi
    elds\__init__.py", line 1072, in __init__
        super(CharField, self).__init__(*args, **kwargs)
      File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\fi
    elds\__init__.py", line 166, in __init__
        self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
      File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\conf\__init_
    _.py", line 55, in __getattr__
        self._setup(name)
      File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\conf\__init_
    _.py", line 41, in _setup
        % (desc, ENVIRONMENT_VARIABLE))
    django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TAB
    LESPACE, but settings are not configured. You must either define the environment
     variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing s
    ettings.
    

here's the script:

    
    
    #!/usr/bin/env python
    import os
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "trailers.settings")
    os.environ["DJANGO_SETTINGS_MODULE"] = "trailers.settings"
    import django
    django.setup()
    import tmdbsimple as tmdb
    from movies.models import Movie
    
    #some code...
    

I can't really figure out what's wrong. Any help is appreciated!


Answer: I would recommend using [Django Custom Management
Commands](https://docs.djangoproject.com/en/1.10/howto/custom-management-
commands/) \- they are really simple to use, they use your settings, your
environment, you can pass parameters and also you can write help strings so
you can use `--help`

Then you just call it with `./manage.py my_custom_command`

Or if you just want to run your script add this to the your script

    
    
    project_path = '/home/to/your/trailers/project/src'
    if project_path not in sys.path:
        sys.path.append(project_path)
    
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "trailers.common")
    
    import django
    django.setup()
    

