Debug true файл настроек django
Файл настроек Django содержит всю конфигурацию вашей установки Django. Этот документ объясняет, как работают настройки и какие настройки доступны.
Using settings in Python code¶
In your Django apps, use settings by importing the object django.conf.settings . Example:
Note that django.conf.settings isn’t a module – it’s an object. So importing individual settings is not possible:
Also note that your code should not import from either global_settings or your own settings file. django.conf.settings abstracts the concepts of default settings and site-specific settings; it presents a single interface. It also decouples the code that uses settings from the location of your settings.
Использование настроек без DJANGO_SETTINGS_MODULE¶
В некоторых случаях вы можете не использовать переменную окружения DJANGO_SETTINGS_MODULE . Например, если вы используете систему шаблонов без Django, вряд ли вы захотите настраивать переменную окружения для настроек.
В этом случае вы можете явно определить настройки Django. Для этого вызовите:
django.conf.settings. configure (default_settings, **settings)¶
Вы можете передать в configure() любое количество именованных аргументов, которые представляют настройки и их значения. Названия аргументов должны быть в верхнем регистре, как и названия настроек. Если какая-то настройка не была указанна в configure() , Django при необходимости будет использовать значение по умолчанию.
Настройка Django таким способом необходима, и рекомендуется использовать, при использовании части фреймверка в другом приложении.
При настройке через settings.configure() Django не меняет переменные окружения (смотрите описание TIME_ZONE , чтобы узнать когда это происходит). Подразумевается, что вы уже полностью контролируете свое окружение.
Altering settings at runtime¶
You shouldn’t alter settings in your applications at runtime. For example, don’t do this in a view:
The only place you should assign to settings is in a settings file.
Calling django.setup() is required for “standalone” Django usage¶
If you’re using components of Django “standalone” – for example, writing a Python script which loads some Django templates and renders them, or uses the ORM to fetch some data – there’s one more step you’ll need in addition to configuring settings.
After you’ve either set DJANGO_SETTINGS_MODULE or called configure() , you’ll need to call django.setup() to load your settings and populate Django’s application registry. For example:
Note that calling django.setup() is only necessary if your code is truly standalone. When invoked by your web server, or through django-admin , Django will handle this for you.
django.setup() may only be called once.
Therefore, avoid putting reusable application logic in standalone scripts so that you have to import from the script elsewhere in your application. If you can’t avoid that, put the call to django.setup() inside an if block:
The Settings Reference Contains the complete list of core and contrib app settings.
Файл настроек Django содержит полную конфигурацию установленного проекта. Этот раздел описывает какие настройки доступны и как они работают.
Learn More
STATIC_ROOT and STATIC_URL ¶
Static files are automatically served by the development server. In production, you must define a STATIC_ROOT directory where collectstatic will copy them.
Available settings¶
For a full list of available settings, see the settings reference .
MEDIA_ROOT and MEDIA_URL ¶
Media files are uploaded by your users. They’re untrusted! Make sure your web server never attempts to interpret them. For instance, if a user uploads a .php file, the web server shouldn’t execute it.
Now is a good time to check your backup strategy for these files.
Support Django!
Customize the default error views¶
Добавление собственных настроек¶
Вы можете добавлять настройки для ваших приложений Django. Просто следуйте правилам:
Названия настроек должны быть в верхнем регистре.
Не изобретайте заново существующие настройки.
Для настроек, которые представляют множество, Django использует списки, но это это не обязательно.
CSRF_COOKIE_SECURE ¶
Critical settings¶
Узнать какие настройки вы поменяли¶
Есть простой способ узнать какие настройки вашего проекта отличаются от настроек по умолчанию. Команда python manage.py diffsettings показывает разницу между текущими настройками и настройками по умолчанию Django.
Подробности смотрите в описании diffsettings .
Either configure() or DJANGO_SETTINGS_MODULE is required¶
If you’re not setting the DJANGO_SETTINGS_MODULE environment variable, you must call configure() at some point before using any code that reads settings.
If you don’t set DJANGO_SETTINGS_MODULE and don’t call configure() , Django will raise an ImportError exception the first time a setting is accessed.
If you set DJANGO_SETTINGS_MODULE , access settings values somehow, then call configure() , Django will raise a RuntimeError indicating that settings have already been configured. There is a property for this purpose:
Also, it’s an error to call configure() more than once, or to call configure() after any setting has been accessed.
It boils down to this: Use exactly one of either configure() or DJANGO_SETTINGS_MODULE . Not both, and not neither.
Доступные настройки¶
Полный список настроек смотрите в разделе о настройках.
Собственные значения по умолчанию¶
Если вы хотите, чтобы значения по умолчанию загружались не с django.conf.global_settings , вы можете указать аргумент default_settings (или первый аргумент) при вызове configure() , который содержит модуль или класс со значениями по умолчанию.
В этом примере настройки по умолчанию загружаются с myapp_defaults , и настройка DEBUG равна True , несмотря на значение из myapp_defaults :
Следующий пример, который использует myapp_defaults как позиционный аргумент, аналогичен предыдущему:
Скорее всего вам не понадобится переопределять их таким способом. Настройки по умолчанию Django достаточно удобны, чтобы использовать их. Обратите внимание, если вы указали собственные настройки по умолчанию, они полностью заменяют настройки Django, поэтому необходимо указать все настройки, которые могут использовать в вашем коде. Полный список можно найти в модуле django.conf.settings.global_settings .
Run manage.py check --deploy ¶
Some of the checks described below can be automated using the check --deploy option. Be sure to run it against your production settings file as described in the option’s documentation.
settings/.env
A defaults for local development. A secret file, to mostly set required environment variables. Set them to empty values if they are not required in local development. We provide defaults here and not in settings/base.py to fail on any other machine if the're missing from the environment.
Использование настроек в коде Python¶
В ваших приложениях Django используйте настройки, импортируя объект django.conf.settings . Пример:
Обратите внимание, что django.conf.settings не является модулем - это объект. Поэтому импорт отдельных настроек невозможен:
Также обратите внимание, что ваш код не должен не импортировать ни из global_settings , ни из вашего собственного файла настроек. django.conf.settings абстрагирует понятия настроек по умолчанию и настроек конкретного сайта; он представляет единый интерфейс. Он также отделяет код, использующий настройки, от местоположения ваших настроек.
Требуется либо configure() , либо DJANGO_SETTINGS_MODULE ¶
Если вы не устанавливаете переменную окружения DJANGO_SETTINGS_MODULE , вы должны вызвать configure() в какой-то момент перед использованием любого кода, который читает настройки.
Если вы не установите DJANGO_SETTINGS_MODULE и не вызовете configure() , Django поднимет исключение ImportError при первом обращении к настройке.
Если вы установите DJANGO_SETTINGS_MODULE , получите каким-то образом доступ к значениям настроек, потом вызовете configure() , Django поднимет RuntimeError , указывая, что настройки уже были настроены. Для этого существует свойство:
Также ошибкой является вызов configure() более одного раза, или вызов configure() после обращения к любой настройке.
Все сводится к следующему: Используйте только один из configure() или DJANGO_SETTINGS_MODULE . Не оба, и не ни то, ни другое.
Доступные настройки¶
Полный список доступных настроек см. в разделе settings reference .
DATABASES ¶
Database connection parameters are probably different in development and in production.
Database passwords are very sensitive. You should protect them exactly like SECRET_KEY .
For maximum security, make sure database servers only accept connections from your application servers.
If you haven’t set up backups for your database, do it right now!
Download:
Offline (Django 4.0): HTML | PDF | ePub
Provided by Read the Docs.
DEBUG ¶
You must never enable debug in production.
You’re certainly developing your project with DEBUG = True , since this enables handy features like full tracebacks in your browser.
For a production environment, though, this is a really bad idea, because it leaks lots of information about your project: excerpts of your source code, local variables, settings, libraries used, etc.
Performance optimizations¶
Setting DEBUG = False disables several features that are only useful in development. In addition, you can tune the following settings.
Настройки по умолчанию¶
Проект Django не обязан определять какие-либо настройки, если в этом нет необходимости. Каждая настройка содержит значение по умолчанию. Эти значния можно найти в модуле django/conf/global_settings.py .
Django использует следующий алгоритм для загрузки настроек:
Загружает настройки из global_settings.py .
Загружает настройки из указанного файла настроек, перезаписывая значения по умолчанию.
Обратите внимание, файла с настройками не должен импортировать global_settings .
Designating the settings¶
When you use Django, you have to tell it which settings you’re using. Do this by using an environment variable, DJANGO_SETTINGS_MODULE .
The value of DJANGO_SETTINGS_MODULE should be in Python path syntax, e.g. mysite.settings . Note that the settings module should be on the Python import search path.
CONN_MAX_AGE ¶
Enabling persistent database connections can result in a nice speed-up when connecting to the database accounts for a significant part of the request processing time.
This helps a lot on virtualized hosts with limited network performance.
Создание собственных настроек¶
Ничто не мешает вам создавать свои собственные настройки для своих Django-приложений, но следуйте этим рекомендациям:
- Имена настроек должны быть прописными.
- Не изобретайте заново уже существующую обстановку.
Для параметров, которые являются последовательностями, Django сам использует списки, но это лишь условность.
The basics¶
A settings file is just a Python module with module-level variables.
Here are a couple of example settings:
If you set DEBUG to False , you also need to properly set the ALLOWED_HOSTS setting.
Because a settings file is a Python module, the following apply:
It doesn’t allow for Python syntax errors.
It can assign settings dynamically using normal Python syntax. For example:
It can import values from other settings files.
Определения файла настроек¶
При использовании Django необходимо указать какие настройки вы используете. Используйте для этого переменную окружения DJANGO_SETTINGS_MODULE .
Значение DJANGO_SETTINGS_MODULE должно содержать путь импорта Python, например mysite.settings . Обратите внимание, модуль с настройками должен быть доступен для импорта.
Error reporting¶
By the time you push your code to production, it’s hopefully robust, but you can’t rule out unexpected errors. Thankfully, Django can capture errors and notify you accordingly.
Изменяем настройки в процессе работы¶
Вам не следует менять настройки в процессе работы приложения. Например, не делайте следующее в представлении:
Единственное место, где вы можете определять настройки – это файл с настройками.
The django-admin utility¶
When using django-admin , you can either set the environment variable once, or explicitly pass in the settings module each time you run the utility.
Example (Unix Bash shell):
Example (Windows shell):
Use the --settings command-line argument to specify the settings manually:
CACHES ¶
If you’re using a cache, connection parameters may be different in development and in production. Django defaults to per-process local-memory caching which may not be desirable.
Cache servers often have weak authentication. Make sure they only accept connections from your application servers.
Follow Us
Environment-specific settings¶
Contents
LOGGING ¶
Review your logging configuration before putting your website in production, and check that it works as expected as soon as you have received some traffic.
See Logging for details on logging.
Update
I wrote a blog post about managing django 's settings with django-split-sttings . Have a look!
I tried that.. ran into a wall once i tried to run my django unit tests.. i just couldn't figure out how to specify which settings file to read from
i got something like this in my code, so i check the settings.DEBUG flag to know if i wanna import stuff.. that flag is always set to false in django unit tests (see here) so my work around is to override them at each test like so
here is another question though: my uwsgi.ini file has different settings across dev/prod.. any idea of how to make it pick values from my settings file?
sorry, i don't get the setup. you can ask a separate question with more details and i will try to help you.
Remember that settings.py is a live code file. Assuming that you don't have DEBUG set on production (which is a best practice), you can do something like:
Pretty basic, but you could, in theory, go up to any level of complexity based on just the value of DEBUG - or any other variable or code check you wanted to use.
The problem with most of these solutions is that you either have your local settings applied before the common ones, or after them.
So it's impossible to override things like
- the env-specific settings define the addresses for the memcached pool, and in the main settings file this value is used to configure the cache backend
- the env-specific settings add or remove apps/middleware to the default one
at the same time.
One solution can be implemented using "ini"-style config files with the ConfigParser class. It supports multiple files, lazy string interpolation, default values and a lot of other goodies. Once a number of files have been loaded, more files can be loaded and their values will override the previous ones, if any.
You load one or more config files, depending on the machine address, environment variables and even values in previously loaded config files. Then you just use the parsed values to populate the settings.
One strategy I have successfully used has been:
- Load a default defaults.ini file
- Check the machine name, and load all files which matched the reversed FQDN, from the shortest match to the longest match (so, I loaded net.ini , then net.domain.ini , then net.domain.webserver01.ini , each one possibly overriding values of the previous). This account also for developers' machines, so each one could set up its preferred database driver, etc. for local development
- Check if there is a "cluster name" declared, and in that case load cluster.cluster_name.ini , which can define things like database and cache IPs
This is as DRY I could get, most (existing) files had just 3 or 4 settings. On top of this I had to manage customer configuration, so an additional set of configuration files (with things like database names, users and passwords, assigned subdomain etc) existed, one or more per customer.
One can scale this as low or as high as necessary, you just put in the config file the keys you want to configure per-environment, and once there's need for a new config, put the previous value in the default config, and override it where necessary.
This system has proven reliable and works well with version control. It has been used for long time managing two separate clusters of applications (15 or more separate instances of the django site per machine), with more than 50 customers, where the clusters were changing size and members depending on the mood of the sysadmin.
Security¶
Because a settings file contains sensitive information, such as the database password, you should make every attempt to limit access to it. For example, change its file permissions so that only you and your web server’s user can read it. This is especially important in a shared-hosting environment.
Custom default settings¶
If you’d like default values to come from somewhere other than django.conf.global_settings , you can pass in a module or class that provides the default settings as the default_settings argument (or as the first positional argument) in the call to configure() .
In this example, default settings are taken from myapp_defaults , and the DEBUG setting is set to True , regardless of its value in myapp_defaults :
The following example, which uses myapp_defaults as a positional argument, is equivalent:
Normally, you will not need to override the defaults in this fashion. The Django defaults are sufficiently tame that you can safely use them. Be aware that if you do pass in a new default module, it entirely replaces the Django defaults, so you must specify a value for every possible setting that might be used in that code you are importing. Check in django.conf.settings.global_settings for the full list.
settings/base.py
These are your mostly vanilla django settings, with a few conditionals and lot's of reading them from the environment. Almost everything is in here, keeping all the purposed environments consistent and as similar as possible.
The main differences are below (I hope these are self explanatory):
The last bit shows the power here. ASSETS_DEBUG has a sensible default, which can be overridden in settings/production.py and even that that can be overridden by an environment setting! Yay!
In effect we have a mixed hierarchy of importance:
- settings/.py - sets defaults based on purpose, does not store secrets
- settings/base.py - is mostly controlled by environment
- process environment settings - 12 factor baby!
- settings/.env - local defaults for easy startup
Hey Janusz. so in the .env file would go all the API keys and auth keys and passwords etc? Just like TWILLIO_API = "abc123"? Or TWILLIO_API = env("TWILLIO_API")?
Yes, but this is only a fallback for environment settings. This file is comes handy for development but is not saved in repo or pushed to production where you should strictly use environment settings or your platform equivalent that will in turn set environment settings for the server process.
How to define production settings? For example when I'm explicitly defining my DJANGO_SETTINGS_MODULE as website/settings/production, the init file is still loading the local.py settings. How can I avoid it, or am I doing something wrong? @JanuszSkonieczny
I manage my configurations with the help of django-split-settings.
It is a drop-in replacement for the default settings. It is simple, yet configurable. And refactoring of your exisitng settings is not required.
Here's a small example (file example/settings/__init__.py ):
Использование django-admin¶
При использовании django-admin вы можете один раз определить переменную окружения, или каждый раз явно указывать модуль с настройками.
Например (Unix Bash shell):
Например (Windows shell):
Используйте аргумент --settings , чтобы явно указать модуль с настройками:
Creating your own settings¶
There’s nothing stopping you from creating your own settings, for your own Django apps, but follow these guidelines:
- Setting names must be all uppercase.
- Don’t reinvent an already-existing setting.
For settings that are sequences, Django itself uses lists, but this is only a convention.
Использование настроек в коде Python¶
В вашем приложении Django вы можете использовать настройки, импортировав django.conf.settings . Например:
Обратите внимание, django.conf.settings – это не модуль, а объект. По этому нельзя импортировать отдельные настройки:
Также ваш код не должен использовать непосредственно global_settings или ваш модуль настроек. django.conf.settings предоставляет единый интерфейс работы с настройками, реализуя концепцию настроек по умолчанию и настроек проекта. Также разделяет код, который использует настройки, и сами настройки.
Назначение настроек¶
Когда вы используете Django, вы должны сообщить ему, какие настройки вы используете. Для этого используется переменная окружения DJANGO_SETTINGS_MODULE .
Значение DJANGO_SETTINGS_MODULE должно быть в синтаксисе пути Python, например, mysite.settings . Обратите внимание, что модуль настроек должен находиться на Python import search path.
Seeing which settings you’ve changed¶
The command python manage.py diffsettings displays differences between the current settings file and Django’s default settings.
For more, see the diffsettings documentation.
SECRET_KEY ¶
The secret key must be a large random value and it must be kept secret.
Make sure that the key used in production isn’t used anywhere else and avoid committing it to source control. This reduces the number of vectors from which an attacker may acquire the key.
Instead of hardcoding the secret key in your settings module, consider loading it from an environment variable:
Настройки по умолчанию¶
Файл настроек Django не должен определять какие-либо параметры, если в этом нет необходимости. Каждая настройка имеет разумное значение по умолчанию. Эти значения по умолчанию находятся в модуле django/conf/global_settings.py .
Вот алгоритм, который Django использует при компиляции настроек:
- Загрузите настройки из global_settings.py .
- Загрузка настроек из указанного файла настроек, при необходимости переопределяя глобальные настройки.
Обратите внимание, что файл настроек не должен не импортировать из global_settings , потому что это избыточно.
Безопасность¶
Поскольку файл настроек содержит конфиденциальную информацию, такую как пароль базы данных, вы должны предпринять все попытки ограничить доступ к нему. Например, измените права доступа к файлу так, чтобы его могли читать только вы и пользователь вашего веб-сервера. Это особенно важно в среде общего хостинга.
settings/local.py
What happens in here, is loading environment from settings/.env , then importing common settings from settings/base.py . After that we can override a few to ease local development.
Пользовательские настройки по умолчанию¶
Если вы хотите, чтобы значения по умолчанию приходили не из django.conf.global_settings , а откуда-то еще, вы можете передать модуль или класс, который предоставляет настройки по умолчанию в качестве аргумента default_settings (или первого позиционного аргумента) в вызове configure() .
В этом примере настройки по умолчанию берутся из myapp_defaults , а параметр DEBUG устанавливается в True , независимо от его значения в myapp_defaults :
Следующий пример, в котором в качестве позиционного аргумента используется myapp_defaults , эквивалентен:
Обычно вам не нужно переопределять значения по умолчанию таким образом. Умолчания Django достаточно примитивны, и вы можете спокойно их использовать. Помните, что если вы передаете новый модуль по умолчанию, он полностью заменяет модуль по умолчанию Django, поэтому вы должны указать значение для всех возможных параметров, которые могут быть использованы в импортируемом коде. Полный список смотрите в django.conf.settings.global_settings .
Для “отдельного” использования Django необходимо вызывать django.setup() ¶
Если вы используете компоненты Django “отдельно” – например, в Python скрипте, который загружает шаблоны Django и рендерит их, или использует ORM для загрузки данных – вам понадобится указать настройки.
После того, как вы указали переменную окружения DJANGO_SETTINGS_MODULE , или вызвали configure() , необходимы вызвать django.setup() , чтобы загрузить настройки и позволить Django загрузить приложения. Например:
Обратите внимание, django.setup() необходим, только если компоненты Django используются действительно отдельно. При запуске через Web-сервер, или django-admin, Django все сделает самостоятельно.
Содержит полный список основных настроек и настроек встроенных приложений.
What is the recommended way of handling settings for local development and the production server? Some of them (like constants, etc) can be changed/accessed in both, but some of them (like paths to static files) need to remain different, and hence should not be overwritten every time the new code is deployed.
Currently, I am adding all constants to settings.py . But every time I change some constant locally, I have to copy it to the production server and edit the file for production specific changes. :(
Edit: looks like there is no standard answer to this question, I've accepted the most popular method.
yo should use base.py file and in your local.py "from .base import *", the same in your production.py "from .base import *", you need run your project with: python manage.py runserver --settings=project_name.settings.local
Безопасность¶
Файл настроек содержит конфиденциальную информацию, например, как пароль к базе данных, вы должны хранить его в безопасности. Например, поменяйте права доступа к файлу, чтобы только вы и пользователь веб-сервера имел к нему доступ. Это особенно важно для хостингов с общим окружением.
Вызов django.setup() необходим для «автономного» использования Django¶
Если вы используете компоненты Django «автономно» - например, пишете сценарий на Python, который загружает некоторые шаблоны Django и отображает их, или использует ORM для получения некоторых данных - вам потребуется еще один шаг в дополнение к настройке параметров.
После того, как вы установили DJANGO_SETTINGS_MODULE или вызвали configure() , вам нужно будет вызвать django.setup() , чтобы загрузить ваши настройки и заполнить реестр приложений Django. Например:
Обратите внимание, что вызов django.setup() необходим только в том случае, если ваш код является действительно автономным. При вызове вашим веб-сервером или через django-admin , Django сделает это за вас.
django.setup() может быть вызван только один раз.
Поэтому избегайте размещения многократно используемой логики приложения в автономных скриптах, чтобы вам не пришлось импортировать из скрипта в другом месте вашего приложения. Если вы не можете этого избежать, поместите вызов django.setup() внутри блока if :
The Settings Reference Содержит полный список настроек основных и дополнительных приложений.
The internet is a hostile environment. Before deploying your Django project, you should take some time to review your settings, with security, performance, and operations in mind.
Performance optimizations are another category of trade-offs with convenience. For instance, caching is useful in production, less so for local development. Error reporting needs are also widely different.
The following checklist includes settings that:
- must be set properly for Django to provide the expected level of security;
- are expected to be different in each environment;
- enable optional security features;
- enable performance optimizations;
- provide error reporting.
Many of these settings are sensitive and should be treated as confidential. If you’re releasing the source code for your project, a common practice is to publish suitable settings for development, and to use a private settings module for production.
Using settings without setting DJANGO_SETTINGS_MODULE ¶
In some cases, you might want to bypass the DJANGO_SETTINGS_MODULE environment variable. For example, if you’re using the template system by itself, you likely don’t want to have to set up an environment variable pointing to a settings module.
In these cases, you can configure Django’s settings manually. Do this by calling:
django.conf.settings. configure (default_settings, **settings)¶
Pass configure() as many keyword arguments as you’d like, with each keyword argument representing a setting and its value. Each argument name should be all uppercase, with the same name as the settings described above. If a particular setting is not passed to configure() and is needed at some later point, Django will use the default setting value.
Configuring Django in this fashion is mostly necessary – and, indeed, recommended – when you’re using a piece of the framework inside a larger application.
Consequently, when configured via settings.configure() , Django will not make any modifications to the process environment variables (see the documentation of TIME_ZONE for why this would normally occur). It’s assumed that you’re already in full control of your environment in these cases.
SESSION_COOKIE_SECURE ¶
Требуется configure() или DJANGO_SETTINGS_MODULE¶
Если вы не указали переменную окружения DJANGO_SETTINGS_MODULE , вы должны вызывать configure() перед кодом, который использует настройки.
Если вы не указали DJANGO_SETTINGS_MODULE и не вызвали configure() , Django вызовет исключение ImportError при первом доступе к настройкам.
Если вы укажите DJANGO_SETTINGS_MODULE , обратитесь к настройкам, а затем вызовите configure() , Django вызовет исключение RuntimeError , указывая, что настройки уже определены. Для проверки этого существует свойство settings.configured .
Также нельзя вызывать configure() несколько раз, или вызывать configure() после обращения к настройкам.
Все сводится к правилам: используйте configure() , или DJANGO_SETTINGS_MODULE . Не оба, и хотя бы один.
Основы¶
Файл настроек – это просто модуль Python с переменными модуля.
Вот пример настроек:
Если установить False в DEBUG , вам также необходимо правильно определить ALLOWED_HOSTS .
Так как файл настроек это модуль Python, верно следующее:
Не допускаются ошибки синтаксиса Python.
Можно динамически определять настройки, используя обычный синтаксис Python. Например:
Можно импортировать значения из других файлов настроек.
TEMPLATES ¶
Enabling the cached template loader often improves performance drastically, as it avoids compiling each template every time it needs to be rendered. When DEBUG = False , the cached template loader is enabled automatically. See django.template.loaders.cached.Loader for more information.
ALLOWED_HOSTS ¶
When DEBUG = False , Django doesn’t work at all without a suitable value for ALLOWED_HOSTS .
You should also configure the web server that sits in front of Django to validate the host. It should respond with a static error page or ignore requests for incorrect hosts instead of forwarding the request to Django. This way you’ll avoid spurious errors in your Django logs (or emails if you have error reporting configured that way). For example, on nginx you might set up a default server to return “444 No Response” on an unrecognized host:
Основы¶
Файл настроек - это просто модуль Python с переменными на уровне модуля.
Вот несколько примеров настроек:
Если вы установили DEBUG в False , вам также необходимо правильно установить параметр ALLOWED_HOSTS .
Поскольку файл настроек является модулем Python, применяются следующие правила:
Он не допускает синтаксических ошибок Python.
Он может назначать параметры динамически, используя обычный синтаксис Python. Например:
Он может импортировать значения из других файлов настроек.
Утилита django-admin ¶
При использовании django-admin вы можете либо установить переменную окружения один раз, либо явно передавать модуль настроек при каждом запуске утилиты.
Пример (оболочка Unix Bash):
Пример (оболочка Windows):
Используйте аргумент командной строки --settings для указания настроек вручную:
ADMINS and MANAGERS ¶
ADMINS will be notified of 500 errors by email.
MANAGERS will be notified of 404 errors. IGNORABLE_404_URLS can help filter out spurious reports.
See How to manage error reporting for details on error reporting by email.
Error reporting by email doesn’t scale very well
Consider using an error monitoring system such as Sentry before your inbox is flooded by reports. Sentry can also aggregate logs.
settings/production.py
For production we should not expect an environment file, but it's easier to have one if we're testing something. But anyway, lest's provide few defaults inline, so settings/base.py can respond accordingly.
The main point of interest here are DEBUG and ASSETS_DEBUG overrides, they will be applied to the python os.environ ONLY if they are MISSING from the environment and the file.
These will be our production defaults, no need to put them in the environment or file, but they can be overridden if needed. Neat!
Настройки сервера (mod_wsgi)¶
При настройках сервера вам понадобиться указать WSGI-приложению какой файл с настройками использовать. Для этого используйте os.environ :
Использование настроек без установки DJANGO_SETTINGS_MODULE ¶
В некоторых случаях вы можете обойтись без переменной окружения DJANGO_SETTINGS_MODULE . Например, если вы используете систему шаблонов самостоятельно, вам, скорее всего, не понадобится устанавливать переменную окружения, указывающую на модуль настроек.
В этих случаях вы можете настроить параметры Django вручную. Сделайте это, вызвав:
django.conf.settings. configure ( default_settings , ** settings )¶
Передайте configure() столько аргументов с ключевыми словами, сколько пожелаете, причем каждый аргумент с ключевым словом представляет собой настройку и ее значение. Имя каждого аргумента должно быть полностью заглавным, с тем же именем, что и настройки, описанные выше. Если конкретная настройка не была передана в configure() и понадобится позже, Django будет использовать значение настройки по умолчанию.
Конфигурирование Django таким образом в основном необходимо - и, более того, рекомендуется - когда вы используете часть фреймворка внутри более крупного приложения.
Следовательно, при настройке через settings.configure() , Django не будет вносить никаких изменений в переменные окружения процесса (см. документацию TIME_ZONE о том, почему это обычно происходит). Предполагается, что в этих случаях вы уже полностью контролируете свое окружение.
EMAIL_BACKEND and related settings¶
If your site sends emails, these values need to be set correctly.
By default, Django sends email from webmaster @ localhost and root @ localhost. However, some mail providers reject email from these addresses. To use different sender addresses, modify the DEFAULT_FROM_EMAIL and SERVER_EMAIL settings.
Просмотр настроек, которые вы изменили¶
Команда python manage.py diffsettings отображает различия между текущим файлом настроек и настройками Django по умолчанию.
Подробнее см. документацию diffsettings .
22 Answers 22
Two Scoops of Django: Best Practices for Django 1.5 suggests using version control for your settings files and storing the files in a separate directory:
The base.py file contains common settings (such as MEDIA_ROOT or ADMIN), while local.py and production.py have site-specific settings:
In the base file settings/base.py :
In the local development settings file settings/local.py :
In the file production settings file settings/production.py :
Then when you run django, you add the --settings option:
The authors of the book have also put up a sample project layout template on Github.
Note that instead of using --settings every time, you could set the DJANGO_SETTINGS_MODULE envvar. This works nicely with, eg, Heroku: set it globally to production, then override it with dev in your .env file.
You may need to change BASE_DIR settings to os.path.dirname(os.path.realpath(os.path.dirname(__file__) + "/.."))
If I set the DJANGO_SETTINGS_MODULE through an environmental variable, do I still need os.environ.setdefault("DJANGO_SETTINGS_MODULE", "projectname.settings.production") in my wsgi.py file? Also, I've set the environmental var using: export DJANGO_SETTINGS_MODULE=projectname.settings.local, but then it is lost when I close the terminal. What can I do to ensure it is saved? Should I add that line to the bashrc file?
You can override what needed in local_settings.py ; it should stay out of your version control then. But since you mention copying I'm guessing you use none ;)
To ease tracking/deployment of new settings, use a "local_settings.py" on the production/testing machines and none on development.
That's the way I do - adding those lines at the end of settings.py so they can override the default settings
This approach means you have unversioned code running in development and production. And every developer has a different code base.I call anti-pattern here.
@pydanny The problem is that Django stores it's configuration in .py file. You can't expect that all developers and production server will use the same settings, so you need to alter this .py file or implement some alternative solution (.ini files, environment etc.).
I prefer calling the module settings_local as opposed to local_settings to group it with settings.py in alphabetical folder listings. Keep settings_local.py out of version control using .gitignore as credentials don't belong to Git. Imagine open sourcing them by accident. I keep in git a template file called settings_local.py.txt instead.
Instead of settings.py , use this layout:
common.py is where most of your configuration lives.
prod.py imports everything from common, and overrides whatever it needs to override:
Similarly, dev.py imports everything from common.py and overrides whatever it needs to override.
Finally, __init__.py is where you decide which settings to load, and it's also where you store secrets (therefore this file should not be versioned):
What I like about this solution is:
- Everything is in your versioning system, except secrets
- Most configuration is in one place: common.py .
- Prod-specific things go in prod.py , dev-specific things go in dev.py . It's simple.
- You can override stuff from common.py in prod.py or dev.py , and you can override anything in __init__.py .
- It's straightforward python. No re-import hacks.
I'm still trying to figure out what to set in my project.wsgi and manage.py files for the settings file. Will you shed some light on this? Specifically, in my manage.py file I have os.environ.setdefault("DJANGO_SETTINGS_MODULE", "foobar.settings") foobar is a folder with an __init__.py file and settings is a folder with an __init__.py file that contains my secrets and imports dev.py, which then imports common.py. EDIT Nevermind, I didn't have a module installed that was required. My bad! This works great!!
Two things: 1) better to set Debug=True in your dev.py rather than =False in your prod.py. 2) Rather than switching in init.py, switch using the DJANGO_SETTINGS_MODULE environment var. This will help with PAAS deployments (e.g. Heroku).
When I use this setup in django 1.8.4 and try runserver I get "django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.", even doh I have SECRET_KEY on my init.py file. Am I missing something?
isn't a the use of something like AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY") more secure? Honest question - I know why you don't want it versioned, but the other alternative is to get it from the environment. Which begs the question of setting the environment variable, of course, but that can be left to your deployment mechanism, no?
I use a slightly modified version of the "if DEBUG" style of settings that Harper Shelby posted. Obviously depending on the environment (win/linux/etc.) the code might need to be tweaked a bit.
I was in the past using the "if DEBUG" but I found that occasionally I needed to do testing with DEUBG set to False. What I really wanted to distinguish if the environment was production or development, which gave me the freedom to choose the DEBUG level.
I'd still consider this way of settings a work in progress. I haven't seen any one way to handling Django settings that covered all the bases and at the same time wasn't a total hassle to setup (I'm not down with the 5x settings files methods).
This is the kind of thing that Django's settings being an actual code file allows, and I was hinting at. I haven't done anything like this myself, but it's definitely the sort of solution that might be a better general answer than mine.
I just ran into this for the first time and chose to (successfully!) use your solution, with a slight difference: I used uuid.getnode() to find uuid of my system. So I'm testing if uuid.getnode() == 12345678901 (actually a different number) instead of the os.environ test you used. I couldn't find documenation to convince me that os.environ['COMPUTERNAME'] is unique per computer.
When using the UUID this solution has proven to be the best and simplest for me. It doesn't require lots of complicated and over-modularized patchwork. In a production environment, you still need to place your database passwords and SECRET_KEY in a separate file that resides outside of version control.
I use a settings_local.py and a settings_production.py. After trying several options I've found that it's easy to waste time with complex solutions when simply having two settings files feels easy and fast.
When you use mod_python/mod_wsgi for your Django project you need to point it to your settings file. If you point it to app/settings_local.py on your local server and app/settings_production.py on your production server then life becomes easy. Just edit the appropriate settings file and restart the server (Django development server will restart automatically).
And what about the local development server? is there a way to tell the django webserver (run using python manage.py runserver ), which settings file to use?
@akv if you add --settings=[module name] (no .py extension) to the end of the runserver command you can specify which settings file to use. If you're going to do that, do yourself a favor and make a shell script/batch file with the development settings configured. Trust me, your fingers will thank you.
this is the solution I use. hacking up a settings file to be used for both production or development is messy
Am I correct in assuming this method requires importing of the settings module via the proxy, django.conf.settings? Otherwise you'd need to edit import declarations to point at the correct settings file when pushing live.
TL;DR: The trick is to modify os.environment before you import settings/base.py in any settings/.py , this will greatly simplify things.
Just thinking about all these intertwining files gives me a headache. Combining, importing (sometimes conditionally), overriding, patching of what was already set in case DEBUG setting changed later on. What a nightmare!
Through the years I went through all different solutions. They all somewhat work, but are so painful to manage. WTF! Do we really need all that hassle? We started with just one settings.py file. Now we need a documentation just to correctly combine all these together in a correct order!
I hope I finally hit the (my) sweet spot with the solution below.
Keep secrets a secret — don't store them in a repo!
Set/read keys and secrets through environment settings, 12 factor style.
Have sensible fallback defaults. Ideally for local development you don't need anything more beside defaults.
…but try to keep defaults production safe. It's better to miss a setting override locally, than having to remember to adjust default settings safe for production.
Have the ability to switch DEBUG on/off in a way that can have an effect on other settings (eg. using javascript compressed or not).
Switching between purpose settings, like local/testing/staging/production, should be based only on DJANGO_SETTINGS_MODULE , nothing more.
…but allow further parameterization through environment settings like DATABASE_URL .
…also allow them to use different purpose settings and run them locally side by side, eg. production setup on local developer machine, to access production database or smoke test compressed style sheets.
Fail if an environment variable is not explicitly set (requiring an empty value at minimum), especially in production, eg. EMAIL_HOST_PASSWORD .
Respond to default DJANGO_SETTINGS_MODULE set in manage.py during django-admin startproject
Keep conditionals to a minimum, if the condition is the purposed environment type (eg. for production set log file and it's rotation), override settings in associated purposed settings file.
Do not let django read DJANGO_SETTINGS_MODULE setting form a file.
Ugh! Think of how meta this is. If you need to have a file (like docker env) read that into the environment before staring up a django process.
Do not override DJANGO_SETTINGS_MODULE in your project/app code, eg. based on hostname or process name.
If you are lazy to set environment variable (like for setup.py test ) do it in tooling just before you run your project code.
Avoid magic and patching of how django reads it's settings, preprocess the settings but do not interfere afterwards.
No complicated logic based nonsense. Configuration should be fixed and materialized not computed on the fly. Providing a fallback defaults is just enough logic here.
Do you really want to debug, why locally you have correct set of settings but in production on a remote server, on one of hundred machines, something computed differently? Oh! Unit tests? For settings? Seriously?
My strategy consists of excellent django-environ used with ini style files, providing os.environment defaults for local development, some minimal and short settings/.py files that have an import settings/base.py AFTER the os.environment was set from an INI file. This effectively give us a kind of settings injection.
The trick here is to modify os.environment before you import settings/base.py .
На сервере ( mod_wsgi )¶
В среде живого сервера вам нужно будет указать приложению WSGI, какой файл настроек использовать. Сделайте это с помощью команды os.environ :
Читайте Django mod_wsgi documentation для получения дополнительной информации и других общих элементов для WSGI-приложения Django.
Support Us
© 2005-2022 Django Software Foundation and individual contributors. Django is a registered trademark of the Django Software Foundation.
A Django settings file contains all the configuration of your Django installation. This document explains how settings work and which settings are available.
Browse
Get Involved
Изменение настроек во время выполнения¶
Вы не должны изменять настройки в своих приложениях во время выполнения. Например, не делайте этого в представлении:
Единственное место, куда следует назначать настройки, - это файл настроек.
Default settings¶
A Django settings file doesn’t have to define any settings if it doesn’t need to. Each setting has a sensible default value. These defaults live in the module django/conf/global_settings.py .
Here’s the algorithm Django uses in compiling settings:
- Load settings from global_settings.py .
- Load settings from the specified settings file, overriding the global settings as necessary.
Note that a settings file should not import from global_settings , because that’s redundant.
On the server ( mod_wsgi )¶
In your live server environment, you’ll need to tell your WSGI application what settings file to use. Do that with os.environ :
Read the Django mod_wsgi documentation for more information and other common elements to a Django WSGI application.
Getting help
Sessions¶
Consider using cached sessions to improve performance.
If using database-backed sessions, regularly clear old sessions to avoid storing unnecessary data.
Читайте также: