首页 > 编程 > Python > 正文

Django中login_required装饰器的深入介绍

2020-01-04 16:15:56
字体:
来源:转载
供稿:网友

前言

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

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

使用方法

1. URLconf中装饰

from django.contrib.auth.decorators import login_required, permission_requiredfrom django.views.generic import TemplateViewfrom .views import VoteViewurlpatterns = [ 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_requiredfrom django.http import HttpResponse@login_requireddef my_view(request): if request.method == 'GET':  # <view logic>  return HttpResponse('result')

3. 装饰类的视图

from django.contrib.auth.decorators import login_requiredfrom django.utils.decorators import method_decoratorfrom django.views.generic import TemplateViewclass 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_requiredfrom django.http import HttpResponseRedirectfrom django.shortcuts import renderfrom django.views.generic import Viewfrom .forms import MyFormclass 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.pyfrom djanco.contrib.auth.decorators import login_requiredfrom django.shortcuts import render_to_response@login_requireddef 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 -->

总结

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


注:相关教程知识阅读请移步到python教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表