Django
Authentication
Login, logout, and protect views with auth decorators.
By EZ4Code Team
authlogindecorators
Code
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect
from django.views.generic import View
@login_required(login_url="/login/")
def dashboard(request):
return render(request, "dashboard.html", {"user": request.user})
@permission_required("articles.add_article", raise_exception=True)
def create_article(request):
...
class ProfileView(LoginRequiredMixin, View):
login_url = "/login/"
def get(self, request):
...
def login_view(request):
if request.method == "POST":
user = authenticate(request, username=request.POST["username"],
password=request.POST["password"])
if user:
login(request, user)
return redirect("dashboard")
return render(request, "login.html")Explanation
authenticate() verifies credentials, login() starts a session, and logout() ends it. The login_required decorator and LoginRequiredMixin gate access for function and class views respectively. permission_required additionally checks a specific model permission assigned to the user.
More Django Snippets
Model Definition
Define a Django model with field types and meta options.
ORM QuerySet
Filter, exclude, annotate and chain QuerySets.
Class-Based Views
Use generic class-based views for common CRUD flows.
URL Routing
Wire URLs to views with path converters and includes.
ModelForms
Build forms from models with validation and widgets.
Template Tags
Use built-in tags and filters in Django templates.