Django中login_required装饰器的深入介绍

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

相关文章

python2.7实现复制大量文件及文件夹资料

需求:拷大量数据,发现有2000G,靠系统的复制功能怕是得好几个小时,于是回来学一手操作,话不多说上代码: 说明:CopyFiles1是可以将sourceDir连子目录一起原样复制到ta...

Python实现简单的文本相似度分析操作详解

本文实例讲述了Python实现简单的文本相似度分析操作。分享给大家供大家参考,具体如下: 学习目标: 1.利用gensim包分析文档相似度 2.使用jieba进行中文分词 3.了解TF-...

Python实现识别手写数字 Python图片读入与处理

Python实现识别手写数字 Python图片读入与处理

写在前面 在上一篇文章Python徒手实现手写数字识别—大纲中,我们已经讲过了我们想要写的全部思路,所以我们不再说全部的思路。 我这一次将图片的读入与处理的代码写了一下,和大纲写的过程一...

Django Rest framework频率原理与限制

Django Rest framework频率原理与限制

前言 开发平台的API接口调用需要限制其频率,以节约服务器资源和避免恶意的频繁调用. DRF就为我们提供了一些频率限制的方法. DRF中的版本、认证、权限、频率组件的源码是一个流程,且...

解决python中 f.write写入中文出错的问题

一个出错的例子 #coding:utf-8 s = u'中文' f = open("test.txt","w") f.write(s) f.close() 原因是编码方式错误,应该...