Search code examples
pythondjangodjango-settings

django local_settings import error


I would like to import a local_settings.py file (which is not in my VCS system) for overriding the DATABASES settings from settings.py

For this purpose I added those lines at the very end of my settings.py file.

try:
    from local_settings import *
except ImportError:
    print('Unable to load local_settings.py:')

When I use a python manage.py diffsettings I see that the DATABASES settings from settings.py is not changed and I get the message Unable to load local_settings.py:

I would like to know why import failed.

This is my project folder architecture:

my_project_folder/
   my_project_folder/
       settings.py
       urls.py
       local_settings.py
       etc...
   app1/
   app2/
   static/
   manage.py
   docker-compose.yml
   etc...

This is the content of my local_settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'postgres',
        'USER': 'postgres',
        'HOST': 'db_my_project',
        'PORT': 5432,
    }
}

And this is the content of the DATABASES settings in settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'mydb',
        'USER': 'my_project',
        'PASSWORD': 'my_password',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

Thanks in advance for your help !


Solution

  • It doesn't work because your forget the . in front of local_settings.py (relative import). Try from .local_settings.py import *, also check that there is an __init__.py in the current folder.

    Concerning settings, I recommend you to store your settings in a settings folder. And create a setting file for each environment. Create a base.py file, which contains base settings and then import it in all other settings files.

    Here is the structure :

    ├── project_name
    │   ├── project_name
    │   │   ├── settings
    │   │   │   ├── __init__.py
    │   │   │   ├── base.py
    │   │   │   ├── dev.py
    │   │   │   ├── staging.py
    │   │   │   └── prod.py
    │   │   ├── __init__.py
    │   │   ├── urls.py
    │   │   └── wsgi.py
    ...
    

    And a settings file (E.g :dev.py or local.py) :

    try:
        from .base import *
    except ImportError:
        print('Unable to import base settings file:')
    
    # ...
    

    Use always relative imports when it's possible.

    Concerning databases, you shouldn't configure them in base.py. Declare them in each specific settings files.