zoukankan      html  css  js  c++  java
  • 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 是更好的选择

  • 相关阅读:
    hdu6060[贪心+dfs] 2017多校3
    Codeforces 547B. Mike and Feet[单调栈/队列]
    Codeforces 545E. Paths and Trees[最短路+贪心]
    gitignore使用
    es学习
    google浏览器安装jsonview
    sychronized关键字底层详解加锁升级过程
    idea 中 “XXX has broken path” 错误解决
    kafka高并发读写的原因
    window redis版本 安装
  • 原文地址:https://www.cnblogs.com/ccorz/p/django-zhong-desetting-quan-ju-bian-liang-de-dao-r.html
Copyright © 2011-2022 走看看