django之上下文处理器

一、上下文处理器的引入

  在模板中想要使用的变量是从视图函数中的context这个上下文的参数中传递进来的,每个视图函数需要什么参数就传什么参数,但是如果大多数的视图函数都需要某个变量,我们再逐个都通过context来传递,岂不是很麻烦,有没有什么办法可以不同传递这些变量,直接使用呢?比如当我们登录后,再去访问其他页面,那么用户名就是我们需要去多次渲染的。

二、上下文处理器的用处

  简而言之就是将我们多次重复使用的某个变量在上下文处理器中传给所有的模板,这样我们就不用再重复传递这个变量了。

三、上下文处理器的用法

  第一步:在主目录下创建存放上下文处理器函数的模块文件。

  第二步:编写上下文处理器函数(上下文处理器函数是一个接受请求对象并返回返回字典对象的一个函数)

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',
            ],
            'builtins': ['django.templatetags.static'],
        },
    },
]
def request(request):
    return {'request': request}

  第三步:注册上下文处理器

def username(request):
    user = request.session.get("username")
    return {"username": user}
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.mycontextprocessors.username'
            ],
            'builtins': ['django.templatetags.static'],
        },
    },
]

  Blog是主目录,先找到文件所在的位置,把自定义的上下文处理器的函数添加到TEMPLATES->OPTIONS->context_processors中。

原文地址:https://www.cnblogs.com/loveprogramme/p/12469924.html