About Restricting a Feature under Development to Particular IPs

You can restrict a feature under development to particular IPs with django-ipware and such a middleware:

app_x/middleware.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class FeatureXMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        from ipware import get_client_ip
        from django.conf import settings

        request.show_feature_x = True
        if settings.X_RESTRICTED_TO_IPS:
            client_ip, is_routable = get_client_ip(request)
            request.show_feature_x = client_ip in settings.X_RESTRICTED_TO_IPS

        response = self.get_response(request)

        return response

settings.py

1
2
3
4
5
6
MIDDLEWARE = [
    ...
    "app_x.middleware.FeatureXMiddleware",
]

X_RESTRICTED_TO_IPS = ["127.0.0.1", "1.2.3.4"]

templates/index.html

1
2
3
4
5
6
7
{% extends "base.html" %}

{% block content %}
    {% if request.show_feature_x %}
        The feature under development.
    {% endif %}
{% endblock %}

Tips and Tricks Programming Django 4.2 Django 3.2 Django 2.2