随笔 - 911  文章 - 5  评论 - 94  阅读 - 243万

设置全局context变量 (显示用户登录名)

比如在每个页面的最上面部分需要显示用户的登录名称,如果不登录则显示为Guest。这部分内容在每个页面都会出现,所以可将该部分内容作为一个公共模板(如userauth.html),如然后在其他模板中进行引用。

userauth.html内容如下:

复制代码
<table class="table table-bordered">
   <thead>
      <tr>
         {% if user_loggedin %}
            <th id="welcome">Welcome: {{user_loggedin}}</th>
            <th id="errorb" style="display:none">eeeeth: {{errorb}}</th>
         {% endif %} 
         <th> <a class="text-info" href="{% url 'aptest:logout' %}">LOGOUT</a> </th>
      </tr>
   </thead>
</table>
复制代码

现在需要在访问每个view的时候,该用户名都可以自动得到,不需要再在每个view中单独定义username,然后再将该username渲染到模板中。

解决方法:

  可以通过使用context_processors设置每个视图的共同变量,Context处理器允许设置一些变量,它们会在每个context中自动被设置好,可以被每个view自动调用,自动渲染到模板中,而不必每次调用 render_to_response() 时都指定。可以参考下C:\Django\django\template\context_processors.py文件中的公共变量。

1.新建C:\Django\workplace\sf\aptest\my_context_processors.py,内容如下:

该文件用于获取用户的username,将其存放于context中,从而可在模板中直接使用。

复制代码
# -*- coding: UTF-8 -*-
#根据用户是否登录获得其username用于显示在Welcome Username。
def Get_user_loggedin(request):
    userinfo = request.session.get('s_username',None)  
    if not userinfo:
        user_loggedin='Guest'   
    else:
        user_loggedin=request.session['s_username']
    context={'user_loggedin':user_loggedin}
    return context
复制代码

2.编辑settings.py,添加如下内容:

复制代码
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
                'aptest.my_context_processors.Get_user_loggedin', #此为新加内容,aptest为该app的名字,Get_user_loggedin为my_context_processors.py中定义的函数名称
            ],
        },
    },
]
复制代码

index view内容如下:

复制代码
@login_req()
def index(request): #主页
    import json
    a=request.POST.get('a')
    b=request.POST.get('b')
    if a is not None and b is not None:
        PLUS=int(a) + int(b)
        MuLT=int(a) * int(b)
        rets={'r1':PLUS,'r2':MuLT}
        retsj=json.dumps(rets)
        return HttpResponse(retsj)
    #context={'user_loggedin':user_loggedin},context #此处无需再定义user_loggedin变量,index.html模板可以自动从my_context_processors.py中得到
    return render(request,'aptest/index.html')
复制代码

index.html模板引用了userauth.html模板内容,具体同http://www.cnblogs.com/dreamer-fish/p/5417190.html。在访问index view时,访问结果如下:

 参考:https://segmentfault.com/a/1190000002461627

 

另一种方式,使用request.user直接显示用户登录名,view中不需要做任何设置(简单):

编辑userauth.html模板文件:

写法一:

复制代码
<table class="table table-bordered">
   <thead>
      <tr>
         {% if request.user.is_anonymous %} <!--判断当前是否为匿名用户,如果是的话,request.user返回AnonymousUser实例-->
            <th id="welcome">Welcome: Guest</th>
         {% else %}
            <th id="welcome">Welcome: {{request.user}}</th>
            <th id="errorb" style="display:none">eeeeth: {{errorb}}</th>
         {% endif %} 
         <th> <a class="text-info" href="{% url 'aptest:logout' %}">LOGOUT</a> </th>
      </tr>
   </thead>
</table>
复制代码

写法二:

复制代码
<table class="table table-bordered">
   <thead>
      <tr>
         {% if request.user.username  %} <!--匿名用户返回None-->  <!-- {% if request.user.is_authenticated  %} 也可以使用-->
            <th id="welcome">Welcome: {{request.user}}</th>
            <th id="errorb" style="display:none">eeeeth: {{errorb}}</th>
         {% else %}
            <th id="welcome">Welcome: Guest</th>
         {% endif %} 
         <th> <a class="text-info" href="{% url 'aptest:logout' %}">LOGOUT</a> </th>
      </tr>
   </thead>
</table>
复制代码

django.contrib.auth.models.AnonymousUser 是一个类,它实现了 django.contrib.auth.models.User 接口,有如下的不同点:

  • id 总是 None.
  • is_anonymous() 返回 True 而不是 False.
  • is_authenticated() 返回 False 而不是 True.

 print request.user

 

posted on   momingliu11  阅读(781)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示