Introduction
Django offers a robust and integrated system for user authentication, encompassing key functionalities such as user registration, login, and logout. This comprehensive guide walks you through the fundamental aspects of incorporating user authentication into your Django application.
User Registration
from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): bio = models.TextField(blank=True)
from django import forms from django.contrib.auth.forms import UserCreationForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ('username', 'email', 'password1', 'password2', 'bio')
from django.shortcuts import render, redirect from django.contrib.auth import login from .forms import CustomUserCreationForm def register(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('home') else: form = CustomUserCreationForm() return render(request, 'registration/register.html', {'form': form})
<!-- registration/templates/registration/register.html -->
{% extends 'base.html' %}
{% block content %}
<h2>User Registration</h2>
<form method="post" action="{% url 'register' %}">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register</button>
</form>
{% endblock %}
from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import authenticate, login def user_login(request): if request.method == 'POST': form = AuthenticationForm(request, 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: login(request, user) return redirect('home') else: form = AuthenticationForm()
return render(request, 'registration/login.html', {'form': form})
<!-- registration/templates/registration/login.html -->{% extends 'base.html' %} {% block content %}
<h2>User Login</h2>
<form method='post' action="{% url 'user_login' %}"
{% csrf_token %} {{ form.as_p }}<button type='submit'>Login</Button>
</form> {% endblock %}
from django.contrib.auth import logout def user_logout(request): logout(request) return redirect('home')