For protecting some views from anonymous users you need to use authentication system. Django provides built-in functions for auth implementation (documentation).
What is authentication? Authentication passes in two steps:
- User identification - searching in database entered username.
- Authentication. If username from first step exists, system comparing password from "password" field with password, saved in database. Before comparison password must be hashed, because database not storing raw password.
Open your Django project and follow this steps:
Create "sign_in" function in views.py:
from django.contrib.auth import authenticate, login
from django.shortcuts import redirect
def sign_in(request):
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('core:profile')
else:
return redirect('core:sign-in')
Create login.html file in templates directory:
<form method="post" action="{% url 'login' %}">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
<input type="submit" value="login">
</form>
Now you need to create url for authentication in urls.py:
from django.urls import path
from .views import sign_in
app_name = 'core'
urlpatterns = [
path('sign-in/', sign_in, name='sign-in'),
]
Checking if user is authenticated in views:
if request.user.is_authenticated:
# Do something for authenticated users.
...
else:
# Do something for anonymous users.
...
Checking if user is authenticated in templates:
{% if user.is_authenticated %}
<p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p>
{% else %}
<p>Please login to see this page.</p>
{% endif %}
Additionally you may decorate view with "login_required":
from django.contrib.auth.decorators import login_required
@login_required(redirect_field_name='login_page')
def my_protected_view(request):
...