{% extends "base.html" %} {% block title %}django-login-default – Demo{% endblock %} {% block content %}

django-login-default

A middleware that makes login required by default — and lets you opt out per view.


The idea

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:

  1. LoginRequiredMiddleware — intercepts unauthenticated requests and redirects to settings.LOGIN_URL.
  2. @no_login_required — decorator for function-based views that should stay public.
  3. NoLoginRequiredMixin — the same thing, but for class-based views.

Setup

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.

Try it

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 %}

protected Dashboard

A regular TemplateView with no special markup. The middleware catches unauthenticated requests and sends you to login.

Go to Dashboard →
public Public Page

Uses NoLoginRequiredMixin to opt out. Anyone can see it, logged in or not.

Go to Public Page →
{% endblock %}