Authentication decorators and redirection
Now that we have learned how to allow ordinary users to log in to our project, we can discover how to restrict content to authenticated users. The authentication module comes with some useful decorators that can be used to secure views according to the current user’s authentication or access.
Unfortunately, if, say, a user named Alice was to log out of Bookr, the profile page would still render and display empty details. Instead of this happening, it would be preferable for any unauthenticated visitor to be directed to the login screen:
Figure 9.6 – An unauthenticated user visits a user profile
The authentication app comes with useful decorators for adding authentication behavior to Django views. In this situation of securing our profile view, we can use the login_required
decorator:
from django.contrib.auth.decorators import login_required @login_required def profile(request): ...