from django.conf import settings from django.core.urlresolvers import reverse, NoReverseMatch from django.http import Http404 class InternalUseOnlyMiddleware(object): """ Middleware to prevent access to the admin if the user IP isn't in the INTERNAL_IPS setting. """ def process_request(self, request): try: admin_index = reverse('admin:index') except NoReverseMatch: return if not request.path.startswith(admin_index): return remote_addr = request.META.get( 'HTTP_X_REAL_IP', request.META.get('REMOTE_ADDR', None)) if not remote_addr in settings.INTERNAL_IPS and not settings.DEBUG: raise Http404