嗨,我正在尝试将身份验证修饰符应用于基于类的视图,但它们似乎无法正常工作,因为当我查看模板时,我没有重定向到默认帐户/登录名/下一个?网址
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_)
答案 0 :(得分:0)
您不能为CBV(基于类的视图)使用django auth装饰器。您可以使用mixins实现此目的。例如,您可以将LoginRequiredMixin用作CBV,而不是login_required装饰器,
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