How to test 404 NOT FOUND with django testing framework? How to test 404 NOT FOUND with django testing framework? django django

How to test 404 NOT FOUND with django testing framework?


Try

response = self.client.get('/something/really/weird/') # note the '/' before something

127.0.0.1:8000/something/really/weird/ is /something/really/weird/ in path relative to root, not

  • something/really/weird
  • something/really/weird/
  • /something/really/weird


The problem is that your ViewFor404 class returns a 200 status code. Look at Django's TemplateView definition:

class TemplateView(TemplateResponseMixin, View):    """    A view that renders a template.    """    def get_context_data(self, **kwargs):        return {            'params': kwargs        }    def get(self, request, *args, **kwargs):        context = self.get_context_data(**kwargs)        return self.render_to_response(context)

so all your class does is a render_to_response, which generates a '200' response.

If you need to override the 404 handler, you should do something more like this in the view:

return HttpResponseNotFound('<h1>Page not found</h1>')

(I don't know the equivalent in class-based views)

Or better yet, can you avoid customizing the View? To customize the 404 display, you can just create a 404.html template (in your site's templates/ directory), and it will be picked up by Django's error viewer.