Django中login_required装饰器的深入介绍

yipeiwu_com7年前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实现名片管理系统

基于python实现名片管理系统

本文实例为大家分享了python实现名片管理系统的具体代码,供大家参考,具体内容如下 主程序: import cards_tools # 无限循环,由用户主动决定什么时候退出 whi...

pycharm 取消默认的右击运行unittest的方法

取消默认的右击运行unittest方法: File-> Settings -> Tools -> Python Integrated Tools -> Defau...

HTML中使用python屏蔽一些基本功能的方法

进行数据解析的理由不计其数,相关的工具和技巧也同样如此。但是,当您需要用这些数据做一些新的事情时,即使有“合适的”工具可能也是不够的。这一担心对于异类数据源的集成同样存在。用来做这项工作...

Python中max函数用法实例分析

本文实例讲述了Python中max函数用法。分享给大家供大家参考。具体如下: 这里max函数是Python内置的函数,不需要导入math模块 # 最简单的 max(1, 2) max...

彻彻底底地理解Python中的编码问题

Python处理文本的功能非常强大,但是如果是初学者,没有搞清楚python中的编码机制,也经常会遇到乱码或者decode error。本文的目的是简明扼要地说明python的编码机制,...