Similar to the UserCreationForm
that was used to to create a new user,the AuthenticationForm
in Django can be used to authenticate a user.
Open the authentication/views.py
file and create a function to authenticate a user.
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import AuthenticationForm
def user_login(request):
if request.method == 'POST':
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
form = AuthenticationForm()
return render(request, 'login.html', {'form': form})
Similarly a route needs to be created for the login function and a template file needs to be created for it.
In the authentication/urls.py
file :
path("login", views.user_login, name="login"),
Create a template file named login.html
and render the form there :
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Login</title>
</head>
<body>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
</body>
</html>
Now when you visit http://127.0.0.1:8000/login,you will see a webpage like this.
On entering the username and password it will authenticate the user and take to home page.
If the username or password is typed wrong, it will show an error message there.
And now as the login page is ready, we can redirect
the user to login page after he clicks the logout button on the home page.
This can be done by editing the logout function in authentication/views.py
file as follows:
def user_logout(request):
logout(request)
return redirect('login')
Now, whenever a user clicks the logout button, he will be redirected to the login page.