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'])
return context
How do I add authentication to django's new class-based views?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
还有一个身份验证混合选项,您可以从中派生视图类。因此,使用 来自 brack3t.com 的 mixin:
然后您可以创建新的“需要身份验证”视图,如下所示
:需要其他补充。感觉很像不重复自己。
There's also the option of an authentication mixin, which you would derive your view class from. So using this mixin from brack3t.com:
you could then create new "authentication required" views like this:
with no other additions needed. Feels very much like Not Repeating Oneself.
文档中有一个关于装饰的部分基于类的视图——如果您只想使用旧的
login_required
等,那就是正确的方法。There's a section in the docs on decorating class-based views -- if you just want to use the old
login_required
etc., that's the way to go.我正在描述一种装饰任何 ListView 的方法:
在编写这样的基于类的视图之后,
您可以直接将任何基于函数的装饰器插入到 url 中。
I am describing a method to decorate any ListView :
After writing a class based view like this,
you can directly insert any function based decorator into the url as so.