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':
return HttpResponse('result')
3. 装饰类的视图
类的方法和独立的函数不完全相同,所以你不可以直接将函数装饰器运用到方法上---你首先需要将它转换成一个方法装饰器
method_decorator装饰器将函数装饰器转换成方法装饰器,这样它就可以用于实例方法。
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView
(1):在方法上进行装饰
class ProtectedView(TemplateView):
template_name ='secret.html'
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(ProtectedView, self).dispatch(*args, **kwargs)
(2):也可以在类上面,传入方法的名字
@method_decorator(login_required, name='dispatch')
classProtectedView(TemplateView):
template_name ='secret.html'
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
网友评论