Redirect anonymous users to log in (don't show them anything)

房东的猫 提交于 2020-03-28 05:09:05

问题


Django 1.9.6.

I want to absolutely disable the whole website from viewing by anonymous users. Anonymous users will always be redirected to login page.

I have created a general view. The problem is that subclasses of GeneralView may not just render a template but perform some calculations or just be of different kinds: DetailView, ListView etc.

class GeneralView(View):
    def get(self, request, template):
        if not request.user.is_authenticated() and request.user.is_active:            
            return redirect("auth_login")
        else:
            return render(request, template)

If I try to inherit, the code gets clumsy:

class HomePageView(GeneralView):
    def get(self, request, template):
        super().get(self, request)

Well, what can I do here? I get error message that my get method doesn't return HttpResponse.

I can rewrite get method of the superclass to return status code. Then check it in the subclass. But this seems to be garbage.

In other words I'm lost in clouds of inheritance. Could you give me a kick here how always to redirect anonymous users to login page, whereas let logged in users see everything.

Thank you in advance.


回答1:


You could use the UserPassesTestMixin for this.

from django.core.urlresolvers import reverse_lazy

class GeneralView(UserPassesTestMixin, View):

    def test_func(self):
        # I assume you missed out the brackets in your question and actually wanted 'if not (request.user.is_authenticated() and request.user.is_active)'
        return request.user.is_authenticated() and request.user.is_active

    login_url = reverse_lazy('auth_login')

The mixin overrides dispatch, so you won't have to call super() when you override get() in your view.

 class HomePageView(GeneralView):
     def get(self, request):
         ...



回答2:


I think your error for get method not returning belongs to not putting a return statement. in fact, in get method of the child class you should do:

class HomePageView(GeneralView):
  def get(self, request, template):
      return super().get(self, request)

That should solve the error



来源:https://stackoverflow.com/questions/37596791/redirect-anonymous-users-to-log-in-dont-show-them-anything

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!