app specific default settings in django?

  • Last Update :
  • Techknowledgy :

I think it's quite common to create a settings.py in your app's package, where you define your settings like this:

from django.conf
import settings
FOO = getattr(settings, 'FOO', "default_value")

In your app you can import them from your app's settings module:

from myapp.settings
import *

def print_foo():
   print FOO

In settings.py, put settings.* before the property.

from django.conf
import settings
settings.FOO = getattr(settings, 'FOO', "default_value")

Why not use AppConfig.ready for setting defaults?

class FooBarConfig(AppConfig):
   name = 'foo_bar'

def ready(self):
   from django.conf
import settings
settings = settings._wrapped.__dict__
settings.setdefault('FOO_BAR_SETTING', 'whatever')

Or better yet define them in clean simple way in a separate module and import them as (or close to how) Settings class does it:

class FooBarConfig(AppConfig):
   name = 'foo_bar'

def ready(self):
   from.import app_settings as defaults
from django.conf
import settings
for name in dir(defaults):
   if name.isupper() and not hasattr(settings, name):
   setattr(settings, name, getattr(defaults, name))

In myapp/settings.py:

from django.conf
import settings

FOO = 'bar'
BAR = 'baz'

_g = globals()
for key, value in _g.items():
   _g[key] = getattr(settings, key, value)

In myapp/other.py:

import myapp.settings

print myapp.settings.FOO

Then in the code:

from.import AppSettings

def in_some_function():
   some_setting = AppSettings.get_some_setting()

Or if you want to load them all in once (but overriding settings in tests won't work for the impacted module):

from.import AppSettings

app_settings = AppSettings()
app_settings.load()

def in_some_function():
   print(app_settings.some_setting)

to create app settings like your example:

from zero_settings
import ZeroSettings

app_settings = ZeroSettings(
   key = "APP",
   defaults = {
      "FOO": "bar"
   },
)

then you can use it like:

from app.settings
import app_settings

print(app_settings.FOO) # which prints bar

user settings will auto override defaults, like:

# this is settings.py, Django settings file
SECRET_KEY = "some_key"
# other settings...
   # the key `APP`
is same key arg
for ZeroSettings
APP = {
   "FOO": "not_bar"
}

Suggestion : 2

Custom default settings,Default settings Seeing which settings you’ve changed ,Altering settings at runtime, Getting Help

ALLOWED_HOSTS = ['www.example.com']
DEBUG = False
DEFAULT_FROM_EMAIL = 'webmaster@example.com'
MY_SETTING = [str(i) for i in range(30)]
export DJANGO_SETTINGS_MODULE = mysite.settings
django - admin runserver
set DJANGO_SETTINGS_MODULE = mysite.settings
django - admin runserver
django - admin runserver--settings = mysite.settings
import os

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'

Suggestion : 3

I'm dividing my site into many small anycodings_python (hopefully reusable) apps, and I'm wondering anycodings_python how best to provide default settings that anycodings_python are overridable by the end-user?,or in your case you can also import it anycodings_python to your settings file and do something anycodings_python like:,It solves this problem in a nice way, I anycodings_python could quote its README here but that is anycodings_python a bit pointless.,My approach is to have a anycodings_python local_settings.py file which supplements anycodings_python the project's setting.py.

The best I've come up with is

myapp / appsettings.py
INSTALLED_APPS = ('my_dependency', 'myapp')
MYVAL = 42

then in settings.py:

from myapp
import appsettings as MYAPP # MYAPP must be UPPER CASE
INSTALLED_APPS = (.....)
INSTALLED_APPS += MYAPP.INSTALLED_APPS # hide / encapsulate sub - dependencies
MYAPP.MYVAL = 5000 # override

and then in view code:

from django.conf
import settings
   ...
   print settings.MYAPP.MYVAL

myapp/appsettings.py

from django.conf
import settings

ANSWER = getattr(settings, "MYAPP_ANSWER", 42)
SOMETHING_ELSE = getattr(settings, "MYAPP_SOMETHING_ELSE", None)

myapp/models.py

from myapp
import appsettings

class Question(object):
   answer = appsettings.ANSWER

local_settings.py:

XINSTALLED_APPS = [
   'myproject.app',
]

settings.py:

INSTALLED_APPS = [
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   ...
]

try:
from local_settings
import *
except ImportError, exp:
   pass

try:
INSTALLED_APPS += XINSTALLED_APPS # defined in local_settings
except NameError:
   pass

I have done In my last project Like this anycodings_python :

from django.conf
import settings

My_APP_ID = getattr(settings, 'My_APP_ID', None)

USER_EMIL_Is = getattr(settings, 'USER_EMIL_Is', Flase)

as an example:

from zero_settings
import ZeroSettings

app_settings = ZeroSettings(
   key = "APP",
   defaults = {
      "INSTALLED_APPS": ["some_app"]
   },
)

and then use it like:

from app.settings
import app_settings

print(app_settings.INSTALLED_APPS)

or in your case you can also import it anycodings_python to your settings file and do something anycodings_python like:

from app_settings
import app_settings

SECRET_KEY = "secret_key"
# other settings....
INSTALLED_APPS = [ *
   app_settings.INSTALLED_APPS
]

Suggestion : 4

App specific default settings in Django?,I'm having some trouble setting default url for specific page in Django,Best practice for defining default app settings for custom django module?,Can I set a specific default time for a Django datetime field?

as an example:

from zero_settings
import ZeroSettings

app_settings = ZeroSettings(
   key = "APP",
   defaults = {
      "INSTALLED_APPS": ["some_app"]
   },
)

and then use it like:

from app.settings
import app_settings

print(app_settings.INSTALLED_APPS)

or in your case you can also import it to your settings file and do something like:

from app_settings
import app_settings

SECRET_KEY = "secret_key"
# other settings....
INSTALLED_APPS = [ *
   app_settings.INSTALLED_APPS
]

I have done In my last project Like this :

from django.conf
import settings

My_APP_ID = getattr(settings, 'My_APP_ID', None)

USER_EMIL_Is = getattr(settings, 'USER_EMIL_Is', Flase)

myapp/appsettings.py

from django.conf
import settings

ANSWER = getattr(settings, "MYAPP_ANSWER", 42)
SOMETHING_ELSE = getattr(settings, "MYAPP_SOMETHING_ELSE", None)

myapp/models.py

from myapp
import appsettings

class Question(object):
   answer = appsettings.ANSWER

local_settings.py:

XINSTALLED_APPS = [
   'myproject.app',
]

settings.py:

INSTALLED_APPS = [
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   ...
]

try:
from local_settings
import *
except ImportError, exp:
   pass

try:
INSTALLED_APPS += XINSTALLED_APPS # defined in local_settings
except NameError:
   pass

Suggestion : 5

An instance of a subclass of AppSettings will now dynamically get settings values from project settings, and cache them. This allows to use the instance the same way in code and tests, without performance loss. See issue #16.,You can easily create your own Setting classes for more complex settings.,Cache is invalidated when Django sends a setting_changed signal (i.e. when using TestCase or override_settings). See issue #16.,Raise ImproperlyConfigured from Setting.check for all errors in a setting.

Installation

pip install django - app - settings

Quick usage

# Define your settings class
import appsettings

class MySettings(appsettings.AppSettings):
   boolean_setting = appsettings.BooleanSetting(
      default = False)
required_setting = appsettings.StringSetting(required = True)
named_setting = appsettings.IntegerSetting(name = 'integer_setting')
prefixed_setting = appsettings.ListSetting(prefix = 'my_app_')

class Meta:
   setting_prefix = 'app_'

# Related settings in settings.py
APP_INTEGER_SETTING = -24
MY_APP_PREFIXED_SETTING = []

# Instantiate your class wherever you need to
appconf = MySettings()
assert appconf.boolean_setting is False # True(
   default value)
assert appconf.required_setting == 'hello'
# raises AttributeError
assert appconf.named_setting < 0 # True
assert appconf.prefixed_setting # False(empty list)

# Values are cached to avoid perf issues
with override_settings(APP_REQUIRED_SETTING = 'hello',
      APP_INTEGER_SETTING = 0):
   #...but cache is cleaned on Django 's setting_changed signal
assert appconf.required_setting == 'hello'
# True
assert appconf.named_setting < 0 # False

# You can still access settings through the class itself(values not cached)
print(MySettings.boolean_setting.get_value()) # explicit call
print(MySettings.boolean_setting.value) # with property

# Run type checking and required presence on all settings at once
MySettings.check() # raises Django 's ImproperlyConfigured (missing required_setting)
# MySettings.check() is best called in django.apps.AppConfig 's ready method

You can easily create your own Setting classes for more complex settings.

import re

import appsettings
from django.core.exceptions
import ValidationError

class RegexSetting(appsettings.Setting):
   def validate(self, value):
   re_type = type(re.compile(r '^$'))
if not isinstance(value, (re_type, str)):
   # Raise ValidationError
raise ValidationError('Value must be a string or a compiled regex (use re.compile)')

def transform(self, value):
   # ensure it always returns a compiled regex
if isinstance(value, str):
   value = re.compile(value)
return value

Suggestion : 6

I hate pasting blobs into my settings.py every time I enable an app.,Create a settings.py file in your app, containing:,App settings are prevented from clobbering built-in settings. They can only add settings.,I'm also aware that this feature has been rejected numerous times on the Django trac. But pasting a bunch of junk into my settings.py each time I add an app is a pain in the ass.

Where you would usually do something like:

from django.conf
import settings
getattr(settings, "MY_SETTING", "DEFAULT")

Create a settings.py file in your app, containing:

MY_SETTING = "DEFAULT"

and do something like:

from djappsettings
import settings
settings.MY_SETTING

Via Pip:

$ pip install djappsettings

Via GitHub:

$ git clone git: //github.com/adammck/djappsettings.git
   $ python djangoappsettings / setup.py install