Django Allow CIDR
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
- breaking Version 0.8.0 dropped support for Python versions older than 3.9 and Django versions earlier than 4.1.
- breaking Version 0.6.0 dropped support for Python 3.6. Users on Python 3.6 must upgrade their Python version before updating to 0.6.0 or newer.
- gotcha The `AllowCIDRMiddleware` *must* be the first middleware in your `MIDDLEWARE` tuple/list. Incorrect placement may lead to Django's built-in `HostHeader` validation rejecting requests before `django-allow-cidr` can process them.
- gotcha If `ALLOWED_CIDR_NETS` is defined and has values, `django-allow-cidr` will internally set Django's `ALLOWED_HOSTS` to `['*']` and handle host header validation itself. While other `ALLOWED_HOSTS` entries will still be considered by the middleware, this internal change is important to understand for debugging.
- deprecated Prior to version 0.5.0, `django-allow-cidr` depended on the `netaddr` library. Version 0.5.0 replaced this dependency with Python 3's built-in `ipaddress` module. While not directly breaking for most users, those relying on `netaddr` being pulled in as a transitive dependency should be aware of this change.
Install
-
pip install django-allow-cidr
Imports
- AllowCIDRMiddleware
from allow_cidr.middleware import AllowCIDRMiddleware
Quickstart
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',
]