Login

Default settings for a app

Author:
phxx
Posted:
June 12, 2008
Language:
Python
Version:
.96
Score:
1 (after 3 ratings)

Save this as conf.py in the app's directory. Now you can do from myapp.conf import settings.

You can access from the imported object every item of your settings.py including the default settings of myapp. Though you don't have to define every setting in settings.py you use in your app. Now you can ommit annoying try...except statements to define defaults directly in the code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import copy
from django.conf import settings as django_settings

default = {
    'YOURAPPS_SETTING_1': True,
    'YOURAPPS_ENTRIES_PER_PAGE': 25,
}

# Make copy of the original settings, to avoid altering the
# project wide settings module.
settings = copy.copy(django_settings)
# Populate default_settings in settings if they aren't set.
for key, value in default.items():
    if not hasattr(settings, key):
        setattr(settings, key, value)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

david_bgk (on June 12, 2008):

What about:

getattr(settings, YOURAPPS_ENTRIES_PER_PAGE, 25)

It doesn't seemed annoying to me...

#

carljm (on June 16, 2008):

This snippet does have the advantage that all your default settings are defined in one place, instead of scattered throughout the application code. Makes it easier for someone picking up the app to see what settings they can define for it.

#

phxx (on June 16, 2008):

It is right what carljm says. First I always used one settings.py file in every app for its default values with: getattr(django_settings, 'MYDEFAULT_SETTING', app_settings.MYDEFAULT_SETTING) But that was to verbose for me. Though now i just import ONE settings module and have all settings in one place including default values.

#

Please login first before commenting.