38. Blocking pages for unauthorized users

Next, we will implement functionality to restrict access to specific pages, ensuring that only authorized users can view them.

To start, we need to import the login_required decorator from Django at the top of the views.py file.

views.py
from django.contrib.auth.decorators import login_required

Note that decorators are a feature in Python that can be applied to functions or methods to extend their functionality. For instance, the @property decorator allows direct access to a method as if it were an attribute, as demonstrated with the final_price method.

In this context, the @login_required decorator restricts access to the view function it decorates, ensuring that only authenticated users can access the associated URL.

We will apply the @login_required decorator to the perform_logout and your_account view functions to restrict access to these endpoints to authenticated users only.

views.py
@login_required
def your_account(request): 
    return render(request, 'user/your_account.html') 
views.py
@login_required
def perform_logout(request) :
    logout(request)
    return redirect('perform_login')

Now, attempting to access either of these view functions will result in error.

Manually entering the youraccount view page by typing it on the url

Due to the use of the @login_required decorator, access to the page is restricted. However, to prevent users from being redirected to an automatic error page (which appends /login to the URL), we will configure Django to redirect users to the perform_login URL. This setup allows users to log in before accessing the restricted page, thereby avoiding an error page.

We will achieve this by defining a variable named LOGIN_URL in the settings.py file and setting its value to 'perform_login'

settings.py
LOGIN_URL = 'perform_login'
Now, when an unauthorized user manually types the your_account URL into the browser, they will be redirected to the login page, as specified by the LOGIN_URL setting.

Last updated