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