django 上下午全局变量
 

context

apps/blog/global_context_processors.py


from .models import *
from django.conf import settings
from django.core.cache import cache


def settings_info(request):
    """
        将settings里面的变量注册为全局变量
    """

    # 获取自定义信息 wy_general_settings表
    sql = Article.objects.raw(
        "SELECT  *  from wy_general_settings")  # 使用原生sql查询

    global_context = cache.get("setting_context")  # 获取该主键的缓存
    if not global_context:  # 如果没有就
        global_context = {raw.varname: raw.value for raw in sql}  # 字典生成式
        cache.set("setting_context", global_context,
                  60 * 60 * 24 * 15)  # 设置该主键的缓存时间,单位秒

    active_categories = Category.objects.filter(active=True).order_by('index')

    return {
        'active_categories': active_categories,  # 分类菜单

        'site_logo_name': global_context['SITE_LOGO'],
        'site_author': global_context['SITE_AUTHOR'],
        'home_site_url': global_context['SITE_URL'],

        'site_logo_name': global_context['SITE_LOGO'],
        'site_author': global_context['SITE_AUTHOR'],
        'home_site_url': global_context['SITE_URL'],
        'site_name': global_context['SITE_NAME'],

        # 'site_index_title': settings.SITE_INDEX_TITLE,
        'site_description': global_context['SITE_DESCRIPTION'],
        'site_keywords': global_context['SITE_KEYWORDS'],
        'ABOUT_CONTENT': global_context['ABOUT_CONTENT'],
        'SITE_TYPE_CHINESE': global_context['SITE_TYPE_CHINESE'],
        'SITE_TYPE_ENGLISH': global_context['SITE_TYPE_ENGLISH'],
        'site_mail': global_context['EMAIL'],
        'my_github': global_context['MY_GITHUB'],
    }

TEMPLATES



    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                ... ...
                'blog.global_context_processors.settings_info',  # 自定义上下文管理器
            ],
        },
    },
]

文章作者: 以谁为师
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源!
              
  目录