Django Allow CIDR

0.8.0 · active · verified Mon Apr 13

django-allow-cidr is a Django Middleware that extends the functionality of Django's `ALLOWED_HOSTS` setting to support CIDR IP ranges. It allows developers to specify IP networks (e.g., '192.168.1.0/24') alongside regular hostnames, which is particularly useful for health checks or internal network access. The current version is 0.8.0, with releases occurring periodically to support new Django and Python versions.

Warnings

Install

Imports

Quickstart

To use django-allow-cidr, install it via pip and then add `AllowCIDRMiddleware` to the very beginning of your `MIDDLEWARE` settings. Define your allowed CIDR ranges in the `ALLOWED_CIDR_NETS` setting in your `settings.py`. Note that if `ALLOWED_CIDR_NETS` is defined, the middleware will internally set `ALLOWED_HOSTS` to `['*']` and take over host header validation.

import os

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'a-very-secret-key-for-development')
DEBUG = True

ALLOWED_HOSTS = [
    'localhost',
    '127.0.0.1',
    # Other hostnames will still work
]

# Define CIDR ranges for allowed hosts
ALLOWED_CIDR_NETS = [
    '192.168.1.0/24',
    '10.0.0.0/8',
    '::1/128' # IPv6 example
]

MIDDLEWARE = [
    'allow_cidr.middleware.AllowCIDRMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

view raw JSON →