Django学习之全局变量

首先说说什么叫全局变量,我们经常在html中使用{{ var }}这样的模板变量,这些变量是我们在视图函数中

提前定义好的变量,通过render()等方法传递到模板中。

但是,还有一类变量,我们并没有在views.py中定义,也能在html中使用该变量,像这样的变量,就叫做

全局变量。

下面来看看如何定义全局变量:

思路:

新建contexts.py文件-->修改settings.py文件-->在html中使用。

1.首先我们需要在项目根目录下的同名目录建立contexts.py文件

     1    #!/bin/bash/python 
     2    # -*- coding: utf-8 -*-
     3    # 全局变量
     4    #
     5    from django.conf import settings
     6    
     7    def lang(request):
     8      return {'lang': settings.LANGUAGE_CODE}

2.修改settings.py中的全局变量templates

    61                'context_processors': [
    62                    'django.template.context_processors.debug',
    63                    'django.template.context_processors.request',
    64                    'django.contrib.auth.context_processors.auth',
    65                    'django.contrib.messages.context_processors.messages',
    66                    'blog.contexts.lang',
    67                ],

上述中'blog.contexts.lang'即是我们定义的方法

3.在模板中使用

 <h3>全局变量lang:{{ lang }}</h3>
 <h3>是否登录:{{request.user.is_authenticated}}</h3>
request.user.is_authenticated为系统自带的全局变量。
tips:
在views.py中必须使用render()或其他能够定向到模板的方法,像HttpResponse()就不行!
附:页面图


原文地址:https://www.cnblogs.com/leomei91/p/7417198.html