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, define a new model that inherits from AbstractBaseUser:
from django.contrib.auth.models import AbstractBaseUser
from django.db import models
class CustomUser(AbstractBaseUser):
username = models.CharField(max_length=255)
email = models.EmailField(unique=True)
Step 2: Create a User Form
Create a form to handle user registration and login:
from django import forms
from .models import CustomUser
class UserRegistrationForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
confirm_password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = CustomUser
fields = ('username', 'email', 'password')
Step 3: Create Views for Registration and Login
Create views to handle user registration and login:
from django.shortcuts import render, redirect
from .forms import UserRegistrationForm
from django.contrib.auth import authenticate, login
def register(request):
if request.method == 'POST':
form = UserRegistrationForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.set_password(form.cleaned_data['password'])
user.save()
return redirect('login')
else:
form = UserRegistrationForm()
return render(request, 'register.html', {'form': form})
Step 4: Add URL Patterns
Add URL patterns to map to the registration and login views:
from django.urls import path
from . import views
urlpatterns = [
path('register/', views.register, name='register'),
path('login/', views.login, name='login'),
]