Welcome to our Django Tutorial on LoginView and LogoutView! Today, we're going to build a simple login and logout system for a web application. By the end of this lesson, you'll have a solid understanding of how Django handles user authentication. π Note: This tutorial assumes you have a basic understanding of Python and Django.
LoginView is a built-in Django class-based view that handles user login functionality. It checks for valid credentials, manages authentication, and redirects users to their desired destination after a successful login. π‘ Pro Tip: You can customize the LoginView to fit your application's needs.
LogoutView is another built-in Django class-based view that handles user logout functionality. It invalidates the user's session and redirects them to the login page.
Before we dive into LoginView and LogoutView, we need to set up authentication in our Django project.
pip install django.contrib.authINSTALLED_APPS = [
# ...
'auth',
# ...
]from django.contrib import admin
from django.urls import path
from django.contrib.auth.views import LoginView, LogoutView
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', LoginView.as_view(), name='login'),
path('logout/', LogoutView.as_view(), name='logout'),
# ...
]Now, let's create a simple form for login and a view to handle it.
accounts:python manage.py startapp accountsfrom django import forms
from django.contrib.auth import authenticate
class LoginForm(forms.Form):
username = forms.CharField(max_length=255)
password = forms.CharField(widget=forms.PasswordInput)
def clean(self):
username = self.cleaned_data['username']
password = self.cleaned_data['password']
user = authenticate(username=username, password=password)
if not user:
raise forms.ValidationError('Invalid login credentials')
return super().clean()from django.shortcuts import render, redirect
from django.contrib.auth import login
from .forms import LoginForm
def login_view(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
user = form.cleaned_data['user']
login(request, user)
next_url = request.GET.get('next')
return redirect(next_url or '/')
else:
form = LoginForm()
return render(request, 'accounts/login.html', {'form': form}){% extends 'base.html' %}
{% block content %}
<h1>Login</h1>
<form method="post">
{% csrf_token %}
{{ form.as_form }}
<button type="submit">Login</button>
</form>
{% endblock %}Now, let's test our login functionality.
python manage.py runserverOpen a web browser and navigate to http://127.0.0.1:8000/login/
Enter valid login credentials and click "Login". You should be redirected to your project's homepage.
Enter invalid login credentials and click "Login". You should see an error message and be unable to log in.
Now that we have a working login functionality, let's implement logout.
# ...
from django.urls import path, reverse_lazy
from django.contrib.auth.views import LoginView, LogoutView
urlpatterns = [
# ...
path('logout/', LogoutView.as_view(next_page=reverse_lazy('login')), name='logout'),
# ...
]Now, when you log in and navigate to your project's homepage, you should see a "Logout" link. Clicking on it will log you out and redirect you to the login page.
What is the purpose of LoginView in Django?
And that's it for today! You now have a working login and logout system in Django. In the next lesson, we'll dive deeper into user registration and account management. π― Pro Tip: Practice by building a simple registration form and customizing the LoginView and LogoutView to fit your application's needs. Happy coding! π‘