简体   繁体   中英

Class Based View to get user authentication in Django

Ok, have a class based view that passes a query_set into my AssignedToMe class. 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. 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 .
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:

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. Gara suggests (it should be the first thing). Also make sure you have the LOGIN_URL defined in your settings.py

Reference: decorating the class

Alternatively you can choose to decorate the url .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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