django local_settings import error

别来无恙 提交于 2020-02-01 06:33:48

问题


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 !


回答1:


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.




回答2:


from rororo.settings import inject_settings

in the end of your's settings.py

inject_settings('settings_local', locals(), True)



来源:https://stackoverflow.com/questions/34044293/django-local-settings-import-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!