django中的setting全局变量的导入

正确使用例子

settings.py

SITE_NAME = “站点名称”
SITE_DESC = "站点描述"

views.py

from django.shortcuts import render
from django.conf import settings


def global_settings(request):
    return {
        'SITE_NAME': settings.SITE_NAME,
        'SITE_DESC': settings.SITE_DESC
    }


def index(request):
    return render(request, 'index.html', locals())

settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'blog.views.global_settings'
            ],
        },
    },
]  

index.html

<h1>{{ SITE_NAME }}</h1>
<h1>{{ SITE_DESC }}</h1>  

为什么不能用import settings

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

So, if you try to access a valid django setting not specified in your settings file you will get an error.

django.conf.settings is not a file but a class making an abstraction of the concepts, default settings and your site-specific settings. Django also does other checks when you use from django.conf import settings.

from django.conf import settings 是更好的选择

posted @ 2017-06-05 11:46  ccorz  阅读(7968)  评论(0编辑  收藏  举报