基于Django类的通用视图和身份验证 [英] Django Class-Based Generic Views and Authentication

查看:254
本文介绍了基于Django类的通用视图和身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Django很新(从1.3开始)。在构建应用程序时,我从第一天开始使用新的基于类的通用视图,使用内置类的组合,并在需要添加到上下文之间进行子类化。



现在我的问题是,我需要回到我的意见,让他们只能访问登录的用户。所有我发现的文档显示了如何使用旧的功能通用视图,而不是基于类的。



这里是一个示例类:

  class ListDetailView(DetailView):
context_object_name =list

def get_queryset(self):
list = get_object_or_404(List,id__iexact = self.kwargs ['pk'])
return List.objects.all()

def get_context_data(self,** kwargs):
context = super(ListDetailView,self).get_context_data(** kwargs)
context ['subscriber_list'] = Subscriber.objects.filter(lists = self.kwargs ['pk'])
返回上下文

如何向django新的基于类的视图添加身份验证?

解决方案

还有一个认证mixin的选项,您将从中导出您的视图类。因此,请使用这个来自lid3t.com的mixin

  class LoginRequiredMixin(object):

@method_decorator(login_required)
def dispatch(self,* args,** kwargs):
return super(LoginRequiredMixin,self).dispatch(* args,** kwargs)

然后你可以创建新的认证需要的意见如下:

  from django.views.generic import DetailView 

class MyDetailView (LoginRequiredMixin,DetailView):
....

,无需其他添加。感觉非常像不重复自己。


I am pretty new to Django (starting with 1.3). In building an app, I went with the new class-based generic views from day one, using a combination of the built in classes and subclassing them where I needed to add to the context.

Now my problem is, I need to go back to my views, and have them accessible only to logged in users. ALL the documentation I have found shows how to do this with the old functional generic views, but not with class-based.

Here is an example class:

class ListDetailView(DetailView):
    context_object_name = "list"

    def get_queryset(self):
        list = get_object_or_404(List, id__iexact=self.kwargs['pk'])
        return List.objects.all()

    def get_context_data(self, **kwargs):
        context = super(ListDetailView, self).get_context_data(**kwargs)
        context['subscriber_list'] = Subscriber.objects.filter(lists=self.kwargs['pk'])
        return context

How do I add authentication to django's new class-based views?

解决方案

There's also the option of an authentication mixin, which you would derive your view class from. So using this mixin from brack3t.com:

class LoginRequiredMixin(object):

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)

you could then create new "authentication required" views like this:

from django.views.generic import DetailView

class MyDetailView(LoginRequiredMixin, DetailView):
    ....

with no other additions needed. Feels very much like Not Repeating Oneself.

这篇关于基于Django类的通用视图和身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆