Please wait...

Raise 503 (SERVICE UNAVAILABLE) error in Django using Middleware

by in Django

It'll helpful for showing on site as maintenance page when site is under developement. Below code will not show site maintenance page to staff user and admin page


from django.conf import settings
from django.urls import resolve
from django.utils.deprecation import MiddlewareMixin

from .views import view_503

class ServiceUnavailableMiddleware(MiddlewareMixin):
    def check_service(self):
        return settings.SERVICE_UNAVAILABLE

    def process_view(self, request, view_func, view_args, view_kwargs):
        url_parts = resolve(request.path)
        if not settings.DEBUG:
            if url_parts.namespace != 'admin' and self.check_service() and not request.user.is_staff:
                return view_503(request)

from django.http import HttpResponse
from django.shortcuts import render

def view_503(request):
    return render(request, '503.html', status=503)



<p>Serivce not available this time, Please try again after some time</p>


Tested on version

Previous Snippet arrow_back

Convert Image(PIL) in Base64