{% extends "base.html" %} {% block title %}django-login-default – Demo{% endblock %} {% block content %}
django-login-defaultA middleware that makes login required by default — and lets you opt out per view.
Instead of adding LoginRequiredMixin or @login_required
to every single view, this middleware flips the default: everything
requires login, and you mark the exceptions.
It ships three things:
LoginRequiredMiddleware — intercepts unauthenticated
requests and redirects to settings.LOGIN_URL.
@no_login_required — decorator for function-based
views that should stay public.
NoLoginRequiredMixin — the same thing, but for
class-based views.
Add the middleware to your settings.py, after
AuthenticationMiddleware:
MIDDLEWARE = [
...
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django_login_default.middleware.LoginRequiredMiddleware",
...
]
LOGIN_URL = "/accounts/login/"
Then mark any view that should be publicly accessible:
# Function-based view
from django_login_default.decorators import no_login_required
@no_login_required
def public_page(request):
...
# Class-based view
from django_login_default.mixins import NoLoginRequiredMixin
class PublicPage(NoLoginRequiredMixin, TemplateView):
template_name = "public.html"
That's it. Every other view is now behind login automatically.
This sample project has two pages you can visit to see the middleware in action.
{% if not user.is_authenticated %}
You're currently not logged in —
credentials are admin / admin.
{% else %}
You're logged in as {{ user.username }}.
{% endif %}
A regular TemplateView with no special markup.
The middleware catches unauthenticated requests and sends you to login.
Uses NoLoginRequiredMixin to opt out. Anyone can see it,
logged in or not.