Django Authentication
Django auth app allows us to log in users and control what they can do within our web app.
Django has a built-in User model with fields like first_name, last_name, email, username, password, etc. We can use the built-in user model or extend it by making another model that has one OneToOneField relationship with the User model.
Django Auth Example
This tutorial uses the built-in User model and authenticate, login, and logout methods from django.contrib.auth app.
django.contrib.auth is a built-in app that is also already listed under settings.py. Below is the module-wise code that follows for the creation of user registration, login, and logout sessions.
models.py
from django.db import models
from django.contrib.auth.models import User
app > urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('login/', views.signin),
path('logout/', views.signout),
path('signup/', views.signup),
]
forms.py
from django.contrib.auth.models import User
from django import forms
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ['username', 'password']
class UserRegistrationForm(forms.ModelForm):
class Meta:
model = User
fields = [
'username',
'password',
'email',
'first_name',
'last_name'
]
Registration, Login and Logout
views.py
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from .forms import UserForm, UserRegistrationForm
from django.http import HttpResponse
from django.contrib.auth.models import User
@login_required
def index(request):
return render(request, 'index.html', {})
def signin(request):
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(
request,
username=username,
password=password
)
if user is None:
return HttpResponse("Invalid credentials.")
login(request, user)
return redirect('/')
else:
form = UserForm()
return render(request, 'login.html', {'form':form})
def signout(request):
logout(request)
return redirect('/')
def signup(request):
if request.method=="POST":
first_name = request.POST['first_name']
last_name = request.POST['last_name']
username = request.POST['username']
password = request.POST['password']
email = request.POST['email']
newuser = User.objects.create_user(
first_name=first_name,
last_name=last_name,
username=username,
password=password,
email=email
)
try:
newuser.save()
except:
return HttpResponse("Something went wrong.")
else:
form = UserRegistrationForm()
return render(request, 'signup.html', {'form':form})
@login_required decorator
login_required decorator allows us to redirect any URL request to a pre-defined LOGIN_URL under settings.py
LOGIN_URL = '/login/'