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:
Post your comments / questions
Recent Article
- How to create custom 404 error page in Django?
- Requested setting INSTALLED_APPS, but settings are not configured. You must either define..
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
- The request was aborted: Could not create SSL/TLS secure channel -Error in Asp.net
Related Article