How to raise 503 error in django?

6.2k views Asked by At

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.

3

There are 3 answers

0
Neeraj Kumar On BEST ANSWER
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)
2
Pablo Vergés On

This kind of errors and responses can be found in django.http.

As you can see, there is no exact match for a "service unavailable".

There are multiple ways of doing this using custom middleware.

You could: Raise an custom exception when the view is processed (you could call it PageInMaintenanceException). Then process your exception returning a rendered template with the right header.

Or simply: Return a rendered template with the right header when the view is processed and the site set under maintenance is called.

0
dfrankow On

To raise a 503 from a view (link):

from django.http import HttpResponse

def my_view(request):
    # Return an "Internal Server Error" 503 response code.
    return HttpResponse(status=503)

To set a custom 500 template (link, docs):

def handler500(request, template_name="500.html"):
    response = render_to_response(template_name, {},
                                  context_instance=RequestContext(request))
    response.status_code = 503
    return response

I have not yet thought through how to resolve the difference between 500 and 503. Perhaps session variables?

Still, I thought I'd post this to get a start on the answer.