Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django handler500 as a Class Based View

Why does this not work

handler500 = TemplateView.as_view(template_name="500.html")

I get the following exception:

Traceback (most recent call last):
  File "/usr/lib/python2.6/wsgiref/handlers.py", line 94, in run    
    self.finish_response()
  File "/usr/lib/python2.6/wsgiref/handlers.py", line 134, in finish_response
    for data in self.result:
  File "/home/hatem/projects/leadsift_app/.virtualenv/lib/python2.6/site-packages/django/template/response.py", line 117, in __iter__
    raise ContentNotRenderedError('The response content must be 'ContentNotRenderedError: The response content must be rendered before it can be iterated over.

I found this set of notes that describe that you are shooting yourself in the foot to use class based views there, why is that?

EDIT: I have ended up using this ... but I am still hoping someone out there would tell me how to get the original oneliner or similar working

class Handler500(TemplateView):
    template_name = "500.html"  
    @classmethod
    def as_error_view(cls):
        v = cls.as_view()
        def view(request):
            r = v(request)
            r.render()
            return r
        return view
handler500 = Handler500.as_error_view()
like image 727
Pykler Avatar asked Nov 29 '12 19:11

Pykler


People also ask

How do I redirect a class-based view in Django?

Django Redirects: A Super Simple Example Just call redirect() with a URL in your view. It will return a HttpResponseRedirect class, which you then return from your view. Assuming this is the main urls.py of your Django project, the URL /redirect/ now redirects to /redirect-success/ .

Why we use class-based views in Django?

The most significant advantage of the class-based view is inheritance. In the class-based view, you can inherit another class, and it can be modified for the different use cases. It helps you in following the DRY principle. You won't have to write the same code over and over in your boilerplate.

Is Django class-based?

Django provides a generic class-based view for that very purpose, TemplateView .


1 Answers

I think its actually quite simple (in Django 1.7 with Python 3.4):

views.py

from django.http import HttpResponse
from django.views.generic.base import View

class Custom500View(View):
    def dispatch(self, request, *args, **kwargs):
        return HttpResponse('My custom django 500 page')

urls.py

from .views import Custom500View

handler500 = Custom500View.as_view()
like image 71
Torsten Engelbrecht Avatar answered Oct 03 '22 20:10

Torsten Engelbrecht