Django中login_required装饰器的深入介绍

yipeiwu_com6年前Python基础

前言

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设计】的支持。   

相关文章

Python的装饰器模式与面向切面编程详解

今天来讨论一下装饰器。装饰器是一个很著名的设计模式,经常被用于有切面需求的场景,较为经典的有插入日志、性能测试、事务处理等。装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大...

python3中类的继承以及self和super的区别详解

python中类的继承: 子类继承父类,及子类拥有了父类的 属性 和 方法。 python中类的初始化都是__init__()。所以父类和子类的初始化方式都是__init__(),但是如...

Python中使用 Selenium 实现网页截图实例

Selenium 是一个可以让浏览器自动化地执行一系列任务的工具,常用于自动化测试。不过,也可以用来给网页截图。目前,它支持 Java、C#、Ruby 以及 Python 四种客户端语言...

pygame实现贪吃蛇游戏(下)

pygame实现贪吃蛇游戏(下)

接着上篇pygame实现贪吃蛇游戏(上)继续介绍 1.豆子的吃掉效果 只需在代码最后移动蛇头的代码后增加一个蛇头和豆子坐标的判断即可 if snake_x == bean_x and...

python中安装Scrapy模块依赖包汇总

本地虚拟环境开发完成之后,上线过程中需要一一安装依赖包,做个记录如下: CentOS 安装python3.5.3 wget https://www.python.org/ftp/py...