As the register and logout functioanlity have been implemented in the previous sections, we can continue to add the login functionality for already registered users to the website. Starting with it, first we shall create a form class for login.
Inside the authentication/forms.py
:
class LoginForm(forms.Form):
email = forms.EmailField(
label='Email Address'
)
password = forms.CharField(
label='Password'
)
class Meta:
fields = ('email', 'password')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field_name, field in self.fields.items():
field.widget.attrs['class'] = 'border border-gray-300 text-black p-2 w-full rounded-md focus:outline-none focus:border-blue-500 '
The LoginForm
class is defined with the email and password field.
Now, the a function can be defined in the authentication/views.py
file to render and load the form and handle the form submission.
from django.contrib.auth import login, authenticate, logout
from django.shortcuts import render, redirect
from .forms import RegistrationForm, LoginForm
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
email = form.cleaned_data.get('email')
password = form.cleaned_data.get('password')
user = authenticate(email=email, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
form = LoginForm()
return render(request, 'authentication/login.html', {'form': form})
This function renders the form if its a get request, otherwise it will get the data from the form and try to authentication with the email and password. If user is not null, then he will be logged in to the website and redirected to the home page.
Also, along with this we shall create a template named login.html
inside the authentication
folder in templates.
{% extends 'base.html' %}
{% block title %}
Login
{% endblock %}
{% block content %}
<div class="bg-gray-900 flex justify-center items-center min-h-screen">
<div class="w-full max-w-md mx-4 bg-gray-700 p-6 rounded-md shadow-md">
<h2 class="text-2xl font-semibold mb-4 text-white text-center">Login</h2>
<form method="post" class="form" enctype="multipart/form-data">
{% csrf_token %}
{% for field in form %}
<div class="mb-4">
<label for="{{ field.id_for_label }}" class="block text-gray-300 text-sm font-bold mb-2">{{ field.label }}</label>
{{ field }}
{% if field.errors %}
<ul class="bg-red-500 text-white p-4">
{% for error in field.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</div>
{% endfor %}
{% if form.non_field_errors %}
<ul class="bg-red-500 text-white p-4">
{% for error in form.non_field_errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
<div class="flex justify-center mt-4">
<button type="submit" class="w-full bg-blue-500 hover:bg-blue-700 text-white font-semibold py-2 px-4 rounded-md transition-colors duration-300">
Login
</button>
</div>
<div class="flex justify-end mt-4">
<a href="{% url 'register' %}" class="underline text-sm text-white-400 hover:text-black-500 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:focus:ring-offset-gray-800">
New User ?
</a>
</div>
</form>
</div>
</div>
{% endblock %}
As similar to the register form, this form is for login, a link is added at the bottom, so if the user has not registered, he can click on the link and go to the register page.
Now the function needs to be registered in the authentication/urls.py
file and a link needs to be added inside the base.html
file.
path('login/', views.user_login, name='login'),
Also in the navbar in base.html
:
<nav class="bg-gray-800 p-4">
<div class="container mx-auto flex justify-between items-center">
<h1 class="text-3xl font-semibold">Campus Connect</h1>
<ul class="flex space-x-4">
{% if user.is_authenticated %}
<li><a href="{% url 'logout' %}">Logout</a></li>
{% else %}
<li><a href="{% url 'login' %}">Login</a></li>
<li><a href="{% url 'register' %}">Register</a></li>
{% endif %}
</ul>
</div>
</nav>
After this, a login link would be visible in the navbar and you will be able to visit the login page by clicking on the link.
After the credentials have been filled and login button is clicked, the user would be able to login to the website.
Also, as we have added a link at the bottom of the login form to redirect to register page, we can also add a link at the bottom of the register form to redirect to login page.
In the authentication/register.html
below the button :
<div class="flex justify-end mt-4">
<a href="{% url 'login' %}" class="underline text-sm text-white-400 hover:text-black-500 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:focus:ring-offset-gray-800">
Already Have an Account ?
</a>
</div>