Redirect to admin for login

前端 未结 4 1712
耶瑟儿~
耶瑟儿~ 2021-01-28 01:15

I have a view defined for a url \'site/main/\'. I would like to be able to have (unauthenticated) users redirected to the default \'/admin/\' page for login, then redirected to

4条回答
  •  暖寄归人
    2021-01-28 01:34

    If you want to redirect to admin for login for specific view, and then to redirect back to the view url after successful login you only need to do two things:

    1. Add LOGIN_URL to settings.py inside your django project module:
    ...
    LOGIN_URL = '/admin/login/'
    
    1. Add @login_required as decorator to your view function inside views.py:
    from django.contrib.auth.decorators import login_required
    ...
    @login_required
    def main(request):
    

    Once you set LOGIN_URL = '/admin/login/' you can use @login_required on whatever view in entire django project and it will redirect to admin for login and after successful login will redirect back to the view url.

    Also now you don't need to use is_authenticated any more inside of a view as Daniel Roseman already said.

    The good thing is that now you also don't need to build a login template and wire it up to the built-in login views.

    What is also good with this approach is the you have flexibility to easily add or remove this kind of authentication to whatever view you want.

提交回复
热议问题