navigation
Python

How to restrict access to the page Access only for logged user in Django

| | django , python

In this tutorial I will show you how to restrict access to the page Access only for logged user in Django.
In order to restrict access to the add_match view such as only logged users can access it, then you can use Django's built-in login_required decorator. This decorator secure the view that can only be accessed by authenticated users. If a user who is not logged tries to access the view, they will be redirected to the login page.

Step 1: Import login_required decorator:

from django.contrib.auth.decorators import login_required

Step 2: Apply login_decorator to the view:

@login_required

def add_match(request):
teams = Team.objects.all()
if request.method == 'POST':
if 'add_match' in request.POST:
team1_id = request.POST['team1']
team2_id = request.POST['team2']
date = request.POST['date']
location = request.POST['location']

team1 = Team.objects.get(id=team1_id)
team2 = Team.objects.get(id=team2_id)
author = request.user.id
match = Match.objects.create(team1=team1, team2=team2, date=date, location=location,author=author)

matches = Match.objects.all().order_by('-date')

return render(request, 'add_match.html',{'teams': teams,'matches': matches})

Step3: Configure Login URL:

LOGIN_URL = '/login/'

VIDEO GUIDE: