Django: Redirect logged in users from login page

前端 未结 9 2417
醉酒成梦
醉酒成梦 2020-11-29 18:02

I want to set up my site so that if a user hits the /login page and they are already logged in, it will redirect them to the homepage. If they are not logged in

9条回答
  •  生来不讨喜
    2020-11-29 18:33

    Since class based views (CBVs) is on the rise. This approach will help you redirect to another url when accessing view for non authenticated users only.

    In my example the sign-up page overriding the dispatch() method.

    class Signup(CreateView):
        template_name = 'sign-up.html'
    
        def dispatch(self, *args, **kwargs):
            if self.request.user.is_authenticated:
                return redirect('path/to/desired/url')
            return super().dispatch(*args, **kwargs)
    

    Cheers!

提交回复
热议问题