djangohttp-status-code-503django-middleware

How to raise 503 error in django?


I want to make site maintenance page and I create singleton model for site maintenance with checkbox field, So when I checked that checkbox from Django admin then the site should show maintenance page if we hit any URL of the website.

I checked 503 status code is related to SERVICE UNAVAILABLE So How can I raise 503 error manually in my code and also want to render a custom template when 503 error raise.


Solution

  • from django.urls import resolve
    from django.utils.deprecation import MiddlewareMixin
    from django.http import HttpResponse
    from django.template import loader
    
    from .models import SiteMaintenance
    
    
    
    class SiteMaintenanceMiddleware(MiddlewareMixin):
        def check_maintenance(self):
            site_maintenance = SiteMaintenance.get_object()
            return site_maintenance.is_maintenance
    
        def process_view(self, request, view_func, view_args, view_kwargs):
            if self.check_maintenance() and not request.user.is_staff:
                return HttpResponse(loader.render_to_string('503.html'), status=503)