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 是更好的选择


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM