Please wait...


Raise 503 (SERVICE UNAVAILABLE) error in Django using Middleware

by in Python

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 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.template import loader

def view_503(request):
    return HttpResponse(loader.render_to_string('503.html'), status=503)



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