Aquí hay dos soluciones. Para ambos puede establecer archivos settings.py
en sus aplicaciones y llenarlos con valores predeterminados.
valor predeterminado Configurar para una sola aplicación
Uso from MYAPP import settings
en lugar de from django.conf import settings
en el código.
Editar YOURAPP/__init__.py
:
from django.conf import settings as user_settings
from . import settings as default_settings
class AppSettings:
def __getattr__(self, name):
# If the setting you want is filled by the user, let's use it.
if hasattr(user_settings, name):
return getattr(user_settings, name)
# If the setting you want has a default value, let's use it.
if hasattr(default_settings, name):
return getattr(default_settings, name)
raise AttributeError("'Settings' object has no attribute '%s'" % name)
settings = AppSettings()
Configurar valores por defecto para un proyecto entero
Uso from MYPROJECT import settings
en lugar de from django.conf import settings
en el código.
Editar MYPROJECT/MYPROJECT/__init__.py
import os, sys, importlib
from . import settings as user_settings
def get_local_apps():
"""Returns the locally installed apps names"""
apps = []
for app in user_settings.INSTALLED_APPS:
path = os.path.join(user_settings.BASE_DIR, app)
if os.path.exists(path) and app != __name__:
apps.append(sys.modules[app])
return apps
class AppSettings:
SETTINGS_MODULE = 'settings'
def __getattr__(self, setting_name):
# If the setting you want is filled by the user, let's use it.
if hasattr(user_settings, setting_name):
return getattr(user_settings, setting_name)
# Let's check every local app loaded by django.
for app in get_local_apps():
module_source = os.path.join(app.__path__[0], "%s.py" % self.SETTINGS_MODULE)
module_binary = os.path.join(app.__path__[0], "%s.pyc" % self.SETTINGS_MODULE)
if os.path.exists(module_source) or os.path.exists(module_binary):
module = importlib.import_module("%s.%s" % (app.__name__, self.SETTINGS_MODULE))
# Let's take the first default value for this setting we can find in any app
if hasattr(module, setting_name):
return getattr(module, setting_name)
raise AttributeError("'Settings' object has no attribute '%s'" % setting_name)
settings = AppSettings()
Esta solución puede parecer más fácil de instalar, pero no garantiza que se devolverá el valor por defecto. Si varias aplicaciones declaran la misma variable en su settings.py, no puede estar seguro de cuál devolverá el valor predeterminado que solicitó.
¿No es esto frágil? ¿No depende de que el proyecto 'settings.py' se importe antes de' app_settings.py'? – Flimm