Django中login_required装饰器的深入介绍


Posted in Python onNovember 24, 2017

前言

Django提供了多种装饰器, 其中login_required可能是经常会使用到的。 这里介绍下四种使用此装饰器的办法。

当然, 在使用前, 记得在工程目录的settings.py中设置好LOGIN_URL

使用方法

1. URLconf中装饰

from django.contrib.auth.decorators import login_required, permission_required
from django.views.generic import TemplateView

from .views import VoteView

urlpatterns = [
 url(r'^about/', login_required(TemplateView.as_view(template_name="secret.html"))),
 url(r'^vote/', permission_required('polls.can_vote')(VoteView.as_view())),
]

2. 装饰基于函数的视图

from django.contrib.auth.decorators import login_required
from django.http import HttpResponse

@login_required
def my_view(request):
 if request.method == 'GET':
  # <view logic>
  return HttpResponse('result')

3. 装饰类的视图

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView

class ProtectedView(TemplateView):
 template_name = 'secret.html'

 @method_decorator(login_required)
 def dispatch(self, *args, **kwargs):
  return super(ProtectedView, self).dispatch(*args, **kwargs)

4. 装饰通过Mixin类继承来实现

from django.contrib.auth.decorators import login_required

from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.views.generic import View

from .forms import MyForm

class LoginRequiredMixin(object):
 @classmethod
 def as_view(cls, **initkwargs):
  view = super(LoginRequiredMixin, cls).as_view(**initkwargs)
  return login_required(view)

class MyFormView(LoginRequiredMixin, View):
 form_class = MyForm
 initial = {'key': 'value'}
 template_name = 'form_template.html'

 def get(self, request, *args, **kwargs):
  form = self.form_class(initial=self.initial)
  return render(request, self.template_name, {'form': form})
 
 def post(self, request, *args, **kwargs):
  # code here

Django 用户登陆访问限制 @login_required

在网站开发过程中,经常会遇到这样的需求:用户登陆系统才可以访问某些页面,如果用户没有登陆而直接访问就会跳转到登陆界面。

要实现这样的需求其实很简单:

      1、在相应的 view 方法的前面添加 django 自带的装饰器 @login_required

      2、在 settings.py 中配置 LOGIN_URL 参数

      3、修改 login.html 表单中的 action 参数

# views.py
from djanco.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response

@login_required
def index(request):
return render_to_response('index.html')
# settings.py
....
LOGIN_URL = '/accounts/login/' # 根据你网站的实际登陆地址来设置
....

如果要使用 django 默认登陆地址,则可以通过在 urls.py 中添加如此配置:

# urls.py
....
url(r'^accounts/login/', views.login),
....
# login.html
<div class="container">
<form class="form-signin" action="/accounts/login/" method="post">
{% csrf_token %}
<!--csrf_token:生成令牌-->
<h2 class="form-signin-heading" align="center">登录系统</h2>
<label for="inputUsername" class="sr-only">username</label>
<input type="text" name="username" id="inputUsername" class="form-control" placeholder="username" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> 记住密码
</label>
</div>
<br />
<button class="btn btn-lg btn-primary btn-block" type="submit">登录</button>
<br />
<span style="color: red;">{{ login_err }}</span>
</form>
</div>
<!-- /container -->

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对三水点靠木的支持。   

Python 相关文章推荐
SublimeText 2编译python出错的解决方法(The system cannot find the file specified)
Nov 27 Python
跟老齐学Python之有容乃大的list(2)
Sep 15 Python
Python编程中运用闭包时所需要注意的一些地方
May 02 Python
基于并发服务器几种实现方法(总结)
Dec 29 Python
python实现闹钟定时播放音乐功能
Jan 25 Python
python如何对实例属性进行类型检查
Mar 20 Python
Python操作mongodb数据库进行模糊查询操作示例
Jun 09 Python
django缓存配置的几种方法详解
Jul 16 Python
基于Django ORM、一对一、一对多、多对多的全面讲解
Jul 26 Python
python如何通过twisted搭建socket服务
Feb 03 Python
浅谈keras中的目标函数和优化函数MSE用法
Jun 10 Python
python中用ctypes模拟点击的实例讲解
Nov 26 Python
Python多进程库multiprocessing中进程池Pool类的使用详解
Nov 24 #Python
pip安装Python库时遇到的问题及解决方法
Nov 23 #Python
python清理子进程机制剖析
Nov 23 #Python
Python3 加密(hashlib和hmac)模块的实现
Nov 23 #Python
Python2.7基于笛卡尔积算法实现N个数组的排列组合运算示例
Nov 23 #Python
深入理解Python3 内置函数大全
Nov 23 #Python
Python内置函数delattr的具体用法
Nov 23 #Python
You might like
《星际争霸II》全新指挥官斯台特曼现已上线
2020/03/08 星际争霸
PHP音乐采集(部分代码)
2007/02/14 PHP
curl不使用文件存取cookie php使用curl获取cookie示例
2014/01/26 PHP
去除php注释和去除空格函数分享
2014/03/13 PHP
php返回当前日期或者指定日期是周几
2015/05/21 PHP
php设计模式之原型模式分析【星际争霸游戏案例】
2020/03/23 PHP
ThinkPHP5分页paginate代码实例解析
2020/11/10 PHP
Js callBack 返回前一页的js方法
2008/11/30 Javascript
一款jquery特效编写的大度宽屏焦点图切换特效的实例代码
2013/08/05 Javascript
jQuery插件ImageDrawer.js实现动态绘制图片动画(附源码下载)
2016/02/25 Javascript
Nodejs中的this详解
2016/03/26 NodeJs
深入解析jQuery中Deferred的deferred.promise()方法
2016/05/03 Javascript
微信小程序  http请求封装详解及实例代码
2017/02/15 Javascript
ES6字符串模板,剩余参数,默认参数功能与用法示例
2017/04/06 Javascript
vue axios同步请求解决方案
2017/09/29 Javascript
在vue中,v-for的索引index在html中的使用方法
2018/03/06 Javascript
vue-cli 组件的导入与使用教程详解
2018/04/11 Javascript
vue用Object.defineProperty手写一个简单的双向绑定的示例
2018/07/09 Javascript
原生JS封装_new函数实现new关键字的功能
2018/08/12 Javascript
[02:01]BBC DOTA2国际邀请赛每日综述:八强胜者组鏖战,中国队喜忧参半
2014/07/19 DOTA
Python日期时间对象转换为字符串的实例
2018/06/22 Python
Django基础知识与基本应用入门教程
2018/07/20 Python
Python 类,property属性(简化属性的操作),@property,property()用法示例
2019/10/12 Python
浅析使用Python搭建http服务器
2019/10/27 Python
Python print不能立即打印的解决方式
2020/02/19 Python
Python3爬虫中Splash的知识总结
2020/07/10 Python
python爬虫线程池案例详解(梨视频短视频爬取)
2021/02/20 Python
关于PySnooper 永远不要使用print进行调试的问题
2021/03/04 Python
信息工程学院毕业生推荐信
2013/11/05 职场文书
《冬阳童年骆驼队》教学反思
2014/04/15 职场文书
2014年幼儿园重阳节活动方案
2014/09/16 职场文书
财务负责人岗位职责
2015/02/03 职场文书
日本读研:怎样写好一篇日本研究计划书?
2019/07/15 职场文书
导游词之台湾阿里山
2019/10/23 职场文书
pycharm无法导入lxml的解决办法
2021/03/31 Python
全面盘点MySQL中的那些重要日志文件
2021/11/27 MySQL