CodeOath
← All posts
Python70 min total · 18 parts

Django Fundamentals: MVT Architecture, the ORM, and Middleware

Contents — Part 14 of 18: Authentication and Authorization
Part 14 of 18 · ~1 min

Authentication and Authorization

from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin

@login_required
def order_detail(request, pk):
    ...

class OrderDetailView(LoginRequiredMixin, DetailView):
    model = Order
    login_url = "/login/"
# In a view, after AuthenticationMiddleware has run:
request.user               # the logged-in User, or an AnonymousUser instance if not logged in
request.user.is_authenticated  # True / False — always safe to check, even when logged out
request.user.has_perm("orders.delete_order")  # permission check

request.user is always present and always an object — never None — because AnonymousUser fills that role when nobody's logged in, which is exactly why .is_authenticated (rather than is not None) is the correct check. Django's built-in permission system (add_<model>, change_<model>, delete_<model>, view_<model>) is created automatically per model and is what has_perm checks against; groups are just named, reusable bundles of permissions.