简体   繁体   English

基于类的视图在Django中获得用户身份验证

[英]Class Based View to get user authentication in Django

Ok, have a class based view that passes a query_set into my AssignedToMe class. 好的,有一个基于类的视图,该视图将query_set传递到我的AssignedToMe类中。 The point of this class based view is to see if a user is logged in and if they are, they can go to a page and it will display all of records that are assigned to their ID. 这种基于类的视图的重点是查看用户是否已登录,如果可以登录,则可以转到页面,该页面将显示分配给其ID的所有记录。 Currently, it is working how I want it to but only if a user is logged in. If a user is not logged in, I get the following error 'AnonymousUser' object is not iterable . 当前,它按我希望的方式工作,但仅在用户登录时有效。如果用户未登录,则会收到以下错误'AnonymousUser' object is not iterable
I want it to redirect the user to the login page if there is no user logged in. Thank you in advance. 如果没有用户登录,我希望它将用户重定向到登录页面。在此先感谢您。 Please look at the screenshot 请看截图

You can create a login required mixin to use in your ClassBasedViews like this: 您可以创建登录所需的mixin,以便在ClassBasedViews中使用,如下所示:

from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required

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

Then use it like @M. 然后像@M一样使用它。 Gara suggests (it should be the first thing). Gara建议(这应该是第一件事)。 Also make sure you have the LOGIN_URL defined in your settings.py 另外,还要确保你的LOGIN_URL在定义settings.py

Reference: decorating the class 参考: 装饰类

Alternatively you can choose to decorate the url . 或者,您可以选择装饰url

我不知道您的ClassBasedView的上下文是什么...但是您可以在调用类之前使用LoginRequiredMixin要求登录:

class ServerDeleteView(LoginRequiredMixin, DeleteView): model = Server success_url = reverse_lazy('ui:dashboard')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM