如何定义自定义Django设置的默认值 [英] How to define a default value for a custom Django setting

查看:614
本文介绍了如何定义自定义Django设置的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django文档提及您可以将自己的设置添加到 django.conf.settings 中。所以如果我的项目的 settings.py 定义

  APPLES = 1 

我可以使用 settings.APPLES



但是,如果我的 settings.py 没有定义该值,则访问 settings.APPLES 显然不行。有没有办法定义 APPLES 的默认值,如果 settings.py 中没有明确的设置,



我最好定义需要设置的模块/包中的默认值。

解决方案

在我的应用程序中,我有一个单独的settings.py文件。在该文件中,我有一个get()函数,在项目settings.py文件中查找,如果没有找到返回默认值。

 从django.conf导入设置

def get(key,default):
getattr(设置,键,默认)


APPLES = get('APPLES',1)

然后我需要访问APPLES我有:从myapp导入设置的

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ c>

这允许项目settings.py中的重写,getattr将首先检查它,如果找到该属性或返回该值,则使用默认定义在您的应用设置文件中。


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.

解决方案

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):
  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.

这篇关于如何定义自定义Django设置的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆