【问题标题】:adding auth decorators to class based views将身份验证装饰器添加到基于类的视图中
【发布时间】:2020-05-26 16:27:52
【问题描述】:

您好,我试图将身份验证装饰器应用于基于类的视图,但它们似乎不起作用,因为当我查看模板时,我没有被重定向到默认帐户/登录/下一个?网址

from .forms import TodoForm
from .models import Todo
from django.template import loader
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator


from django.views.generic import (
    CreateView,
    ListView,
    DetailView,
    UpdateView,
    DeleteView
)
from django.urls import reverse
from django.shortcuts import render, get_object_or_404


# Create your views here.
@method_decorator(login_required, name='dispatch')
class TodoListView(ListView):
    template_name = 'ToDo/todo_list.html'
    queryset = Todo.objects.all()

@method_decorator(login_required, name='dispatch')
class TodoDetailView(DeleteView):
    template_name = 'ToDo/todo_detail.html'
    queryset = Todo.objects.all()

    def get_object(self):
        id_ = self.kwargs.get("id")
        return get_object_or_404(Todo, id=id_)


【问题讨论】:

    标签: django python-decorators django-class-based-views


    【解决方案1】:

    您不能将 django auth 装饰器用于 CBV(基于类的视图)。您可以使用 mixins 来实现这一点。例如,代替 login_required 装饰器,您可以将 LoginRequiredMixin 用于 CBV,

    from django.contrib.auth.mixins import LoginRequiredMixin
    
    class MyView(LoginRequiredMixin, View):
    
        login_url = '/login/'
        redirect_field_name = 'redirect_to'
    

    查看文档https://docs.djangoproject.com/en/3.0/topics/auth/default/#the-loginrequired-mixin

    【讨论】:

    • 好吧,尽管我从 djangodocs 获得了基于类的视图中的装饰器用法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 2015-08-03
    • 1970-01-01
    • 2014-10-20
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多