Render a template within def get_object instead of raise raise Http404


In the get_object method of class views, can I direct the user to a template instead of returning the object if an if statement fails?

Currently raise Http404("Some message.") works good but it doesn’t look nice, I want to use my own template.

I’m trying to do this but with templates:

def get_object(self):
    product = Product.objects.get(slug=self.kwargs.get('slug'))
        if product.deleted == False:
            if product.out_of_stock == False:
                return product
                raise Http404("This product is sold out.")
                # return reverse("404-error", kwargs={"error": "sold-out"})
                # return render(request, "custom_404.html", {"error": "sold_out"})
            raise Http404("This product is no longer available.")
            # return reverse("404-error", kwargs={"error": "deleted"})
            # return render(request, "custom_404.html", {"error": "deleted"})

My main goal is to just avoid getting the object. I know I can perform the if statement in the get_context_data method, however I wasn’t sure for objects containing sensitive data if there would be any way for a user to access it once it’s in the get_object, so I just wanted to avoid getting the object altogether if the condition fails and display a template to the user.


You can use your own view when a 404 error occurs, first create a custom view:


from django.shortcuts import render

def handler404(request, *args, **kwargs):
    return render(request, template_name='custom_404.html', status=404)

Now you need to override the default 404 view, adds this in your main file:

handler404 = 'appname.views.handler404'  # Replaces  appname with the name of the app that contains the custom view

Now you can simply raise a Http404 exception to show your custom template (you can keep your actual code).

Answered By – RedWheelbarrow

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published