Why do we want to protect our views?

When creating a Django web application, there will typically be a need for authentication and user login. The general implication here is that we want logged-in users to see content that is applicable to them and only to them. What we don't want is for outsiders to be able to access just anything.

How do we solve this problem?

Right, to solve this problem we would need to protect our views in Django, and to help us do this we will use the login required decorator.

The login required decorator helps us to enforce this protection by forcing the user to authenticate themselves performing being granted access to certain pages within a web application.

So, let's get started with an example...

Step 1:

Go to your views.py file and import the login required decorator as follows:

# views.py

from django.contrib.auth.decorators import login_required

Step 2:

Now attach the login_required decorator to the view that you want to protect, along with the login_url destination that you want users to be redirected to when they are not logged in.

Here is a typical example of how that may look.

# views.py

@login_required(login_url='/example url - to redirect to/')
def private_dashboard(request):
    return HttpResponse("This page is for logged in users only!")