比如在每个页面的最上面部分需要显示用户的登录名称,如果不登录则显示为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

设置全局context变量 (显示用户登录名)的更多相关文章

  1. logname - 显示用户登录名

    总览 (SYNOPSIS) logname [OPTION]... 描述 (DESCRIPTION) 显示 当前用户 的 名字. --help 显示 帮助信息, 然后 结束. --version 显示 ...

  2. UBUNTU 下设置全局 path变量

    全局的对所有用户都可以的使用的PATH: 可以通过修改配置文件: /etc/bashrc 和 /etc/profile 来时配置, 全局的PATH; 例如: vi /etc/profile 在最后后加 ...

  3. java web设置全局context参数

    先在生成的web.xml文件中配置全局参数变量(Parameter:参数) <web-app> <context-param> 设置parameter(参数)的识别名字为adm ...

  4. centos7 设置grub密码及单用户登录实例

    centos7与centos6在设置grub密码的操作步骤上有很大的差别,特此记录供以后查用 grub加密的目的: 防止不法分子利用单用户模式修改root密码 给grub加密可以采用明文或者加密的密文 ...

  5. day01-3-界面显示&用户登录&餐桌状态显示

    满汉楼01-3 4.功能实现02 4.2菜单界面显示 4.2.1功能说明 显示主菜单.二级菜单和退出系统功能 4.2.2代码实现 先搭建界面显示的大体框架,具体的功能后面再实现 创建MHLView类: ...

  6. Android设置全局Context

    新建一个java继承Application类 import android.app.Application; import android.content.Context; /** * 编写自定义Ap ...

  7. 设置Fedora能够使用root用户登录

    1. 切换到root工作环境,因为一下操作必须拥有root权限 [ha@localhost ~]$ su root密码: 2. 编辑/etc/pam.d/gdm [root@localhost ha] ...

  8. ssh公钥认证原理及设置root外的其他用户登录ssh

    1)创建其他用户 useradd [-d 登录目录] [-G ssh][用户名]  一定要将用户添加到ssh组不然无法没有权限登录ssh 2)设置ssh不允许root登录 vi /etc/ssh/ss ...

  9. MOss213获得用户登录名

    因SharePoint2013默认使用claims based authentication,所以其帐号会是i:0#.w|/domain name这样的格式,如何去掉前面的内容,只保留登录帐号呢? 参 ...

随机推荐

  1. 用python写一个爬虫——爬取性感小姐姐

    忍着鼻血写代码 今天写一个简单的网上爬虫,爬取一个叫妹子图的网站里面所有妹子的图片. 然后试着先爬取了三页,大概有七百多张图片吧!各个诱人的很,有兴趣的同学可以一起来爬一下,大佬级程序员勿喷,简单爬虫 ...

  2. WinForm 多语言处理

    多语言处理工具我使用的是  SailingEase .NET Resources Tool ,好处是导出一个Excel,把具体翻译工作交给专业的人来做,翻译ok后再导入,缺点就是后续更改麻烦,添加一个 ...

  3. docker 简单安装java web项目

    前言: Docker 是一个开源的应用容器引擎,基于 Go 语言 并遵从Apache2.0协议开源. Docker 可以让开发者打包他们的应用以及依赖包到一个轻量级.可移植的容器中,然后发布到任何流行 ...

  4. 如何移动 nuget 缓存文件夹

    本文告诉大家如何移动 nuget 缓存文件夹. 因为 nuget 文件夹一般比较大,现在我的 nuget 文件夹有 10 G,默认的 nuget 文件夹是在C盘,所以需要移动他. 可以使用下面的代码查 ...

  5. 【JavaScript 从零开始】表达式和运算符(1)

    原始表达式 最简单的表达式是"原始表达式"(primary expression).JavaScript中的原始表达式包含常量或直接量.关键字和变量. // 常量或直接量 1.23 ...

  6. spring boot入门笔记 (三) - banner、热部署、命令行参数

    1.一般项目启动的时候,刚开始都有一个<spring>的标志,如何修改呢?在resources下面添加一个banner.txt就行了,springboot会自动给你加载banner.txt ...

  7. ZAB 算法

    ZAB (Zookeeper Atomic Broadcast )  zookeeper原子消息广播协议 保证:分布式数据一致性  所有事务请求必须由一个全局唯一的服务器来协调处理,这样的服务器被称为 ...

  8. excel的列生成算法

    echo '<pre>'; $i = 1; while($i < 703){ $char1 = floor($i / 26); $char2 = $i % 26; if($i % 2 ...

  9. javascript之for循环的几种写法

    背景 javascript中的for循环选择多种多样,可你知道其中的差别在哪里吗?什么时候又该用哪种循环才是最佳策略?以上这些是本文想讨论的,欢迎交流. 说明 1.20年前的for循环 //20年前的 ...

  10. AIX修改时区,配置NTP服务

    AIX修改时区 smitty --> System Environments -->Change/Show Data and Time -->Change Time Zone Usi ...