Django 上下文处理器

上下文处理器可以在 settings 中的  TEMPLATES 模板配置内看都有什么上下文处理器

也可以自己写好方法在模板配置内添加

定义的方法

#导入时间模块
import datetime

#定义一个上下文处理器方法
def get_daytime(reqeust):
    ip = reqeust.META['REMOTE_ADDR']
    #获取当前时间

    nowtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    my_hour = int(datetime.datetime.now().strftime('%H'))
    if my_hour > 1 and my_hour <= 7:
        now_str = '早上好'
    elif my_hour > 7 and my_hour <= 11:
        now_str = '上午好'
    elif my_hour > 11 and my_hour <= 18:
        now_str = '下午好'
    else:
        now_str = '晚上好'
    #给模板传递参数
    return locals()

将写好方法在模板配置内添加

#模板配置
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',
                #定义自定义上下文处理器的位置
                'supermarket.context_processor.get_daytime'
            ],
        },
    },
]

 

posted @ 2019-02-21 21:08  TheoldmanPickgarbage  阅读(191)  评论(0编辑  收藏  举报