Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a default value for a custom Django setting

The Django documentation mentions that you can add your own settings to django.conf.settings. So if my project's settings.py defines

APPLES = 1 

I can access that with settings.APPLES in my apps in that project.

But if my settings.py doesn't define that value, accessing settings.APPLES obviously won't work. Is there some way to define a default value for APPLES that is used if there is no explicit setting in settings.py?

I'd like best to define the default value in the module/package that requires the setting.

like image 361
sth Avatar asked Apr 08 '11 22:04

sth


People also ask

What is Django default value?

The default is False . blank: If True , the field is allowed to be blank in your forms. The default is False , which means that Django's form validation will force you to enter a value.

How do I change Django settings?

Default settings 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.

What does Django setup () do?

It is used if you run your Django app as standalone. It will load your settings and populate Django's application registry. You can read the detail on the Django documentation.

Where is import settings in Django?

import settings will import the first python module named settings.py found in sys. path . Usually (in default django setups) it allows access only to your site defined settings file, which overwrites django default settings ( django. conf.


2 Answers

In my apps, I have a seperate settings.py file. In that file I have a get() function that does a look up in the projects settings.py file and if not found returns the default value.

from django.conf import settings  def get(key, default):     return getattr(settings, key, default)   APPLES = get('APPLES', 1) 

Then where I need to access APPLES I have:

from myapp import settings as myapp_settings  myapp_settings.APPLES 

This allows an override in the projects settings.py, getattr will check there first and return the value if the attribute is found or use the default defined in your apps settings file.

like image 137
Mike Ramirez Avatar answered Oct 05 '22 13:10

Mike Ramirez


How about just:

getattr(app_settings, 'SOME_SETTING', 'default value') 
like image 41
Charlie Avatar answered Oct 05 '22 14:10

Charlie