intermediate#Django#Authentication#User Management
Using Django's Built-in Authentication System
Learn how to use Django's built-in authentication system to manage user accounts and permissions.
Introduction to Django Authentication
Django comes with a built-in authentication system that allows you to manage user accounts and permissions. In this tutorial, we will explore how to use Django's authentication system.
Step 1: Create a User Model
Django provides a built-in User model that you can use to create user accounts. To create a custom user model, create a new model in models.py:
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
email = models.EmailField(unique=True)
Step 2: Create a User Form
Create a form to create new users in forms.py:
from django import forms
from .models import CustomUser
class UserForm(forms.ModelForm):
class Meta:
model = CustomUser
fields = ('username', 'email', 'password')
Step 3: Create Views for User Registration and Login
Create views to handle user registration and login in views.py:
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from .forms import UserForm
def register(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect('home')
else:
form = UserForm()
return render(request, 'register.html', {'form': form})
def login_view(request):
if request.method == 'POST':
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('home')
return render(request, 'login.html')
Step 4: Add URL Patterns for User Registration and Login
Add URL patterns to urls.py:
from django.urls import path
from . import views
django.urls.path('register/', views.register, name='register')
django.urls.path('login/', views.login_view, name='login')