我正在使用django 1.8开发一个网站。这是其中一个视图的示例:
class ProfileView(View):
template_name = 'index.html'
# Return profile of any role (client/employee/admin)
# Login required
def get(self, request, *args, **kwargs):
try:
profile = Profile.objects.get(user=request.user)
agency = None
if request.user.is_employee():
employee = EmployeeProfile.objects.get(profile=profile)
agency = employee.agency
if request.user.is_manager():
agency = Agency.objects.get(manager=request.user)
except (Profile.DoesNotExist, EmployeeProfile.DoesNotExist, Agency.DoesNotExist) as e:
return HttpResponseRedirect('/404')
return render(request, self.template_name, {"profile": profile, "agency": agency})
# Client sign up
# No decorator is needed
def post(self, request):
sign_up = SignUpForm(request.POST, request.FILES)
response = json.loads(utils.create_user(sign_up,request.POST['avatar']))
if response['profile'] is None:
return JsonResponse({"code": 400, "response": response['message']})
profile = serializers.deserialize("json", response['profile']).next().object
group = Group.objects.get(name='clients')
profile.user.groups.add(group)
return HttpResponseRedirect('/')
问题是,我可以根据对控制器(视图)的请求类型设置不同的装饰器吗?
答案 0 :(得分:6)
自Django 1.9 according to the doc起,可以通过以下方式应用装饰器:
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
@method_decorator(login_required, name='dispatch')
class YourClassBasedView(TemplateView):
...
其中name
是要修饰的方法的名称。
或在装饰很少的情况下:
from django.contrib.auth.decorators import login_required
from django.views.decorators.cache import never_cache
from django.utils.decorators import method_decorator
decorators = [never_cache, login_required]
@method_decorator(decorators, name='dispatch')
class YourClassBasedView(TemplateView):
...
答案 1 :(得分:3)
您需要将装饰器应用于基于类的视图的dispatch方法。这可以按如下方式完成:
class ProfileView(View):
@youdecorator
def dispatch(self,request,*args,**kwargs):
return super(ProfileView,self).dispatch(request,*args,**kwargs)
//Rest of your code.
答案 2 :(得分:3)
有一个非常简单的解决方案可以达到你想要的效果,并不意味着装饰dispatch
方法。您必须使用method_decorator
覆盖您的方法(获取/发布)并将装饰器调用(不是装饰器本身)作为参数传递。
在你的情况下,它将是:
from django.utils.decorators import method_decorator
class ProfileView(View):
template_name = 'index.html'
# Return profile of any role (client/employee/admin)
@method_decorator(login_required())
def get(self, request, *args, **kwargs):
...
# Client sign up
# No decorator is needed
def post(self, request):
...
注意login_required
装饰者的画面。
你可以传递任何面向函数的装饰器,甚至是自定义装饰器。例如:
def white_list_check():
def decorator(func):
def wrapper(request, *args, **kwargs):
ip = request.META.get('REMOTE_ADDR', '0.0.0.0')
if ip in WHITE_LIST:
return func(request, *args, **kwargs)
else:
return HttpResponseForbidden()
return wrapper
return decorator
然后,再次:
class YourView(View):
@method_decorator(white_list_check())
def get(self, request):
...
答案 3 :(得分:2)
可以在urls.py中使用像never_cache这样的装饰器而不是旧的方式:在views.py中
e.g。 never_cache装饰器:
旧样式views.py:
from django.views.decorators.cache import never_cache
@never_cache
def oldstyle_view(request):
# and so on
在使用基于类的视图时,在urls.py中:
from django.views.decorators.cache import never_cache
urlpatterns = patterns('',
(r'someurl/^$', never_cache(SomeClassBasedView.as_view())),
)
编辑2015年8月1日
注意:对于那些没有在views.py中定义完整视图的视图,这可以很方便,除此之外,装饰器也可以应用于视图中的depatch方法。
答案 4 :(得分:1)
您可以覆盖dispatch
方法并根据请求类型调用不同的装饰器:
from django.utils.decorators import method_decorator
class ProfileView(View):
...
def dispatch(self, *args, **kwargs):
dispatch_method = super(ProfileView, self).dispatch
if self.request.method == 'GET':
dispatch_method = method_decorator(my_get_decorator)(dispatch_method)
elif self.request.method == 'POST':
dispatch_method = method_decorator(my_post_decorator)(dispatch_method)
return dispatch_method(*args, **kwargs)