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

  • 相关阅读:
    如何重新加载 Spring Boot 上的更改,而无需重新启动服务器?
    FileUpload拦截器
    aspnet网页刷新
    查看SQL表的详细信息
    学习GDI+ (1)
    设计模式简单工厂模式
    对数据库表操作,统一的方法。
    随机产生300道四则运算
    略谈从计算机专业,再到软件构建的初识
    #在android studio中维护日程管理系统
  • 原文地址:https://www.cnblogs.com/ccorz/p/django-zhong-desetting-quan-ju-bian-liang-de-dao-r.html
Copyright © 2011-2022 走看看