[Fixed]-How do I redirect from a Django DetailView when the specified object doesn't exist?

23👍

The DetailView‘s get_object method raises an Http404 exception if the object doesn’t exist in the queryset. Instead of overriding the get_object method you could catch the exception in the view’s get method:

from django.http import Http404
from django.views.generic import DetailView
from django.shortcuts import redirect

class MyDetailView(DetailView):

    def get(self, request, *args, **kwargs):
        try:
            self.object = self.get_object()
        except Http404:
            # redirect here
            return redirect(url)
        context = self.get_context_data(object=self.object)
        return self.render_to_response(context)

6👍

For common cases

from django.http import Http404
from django.shortcuts import redirect
from django.urls import reverse
from django.views.generic import DetailView


class MyDetailView(DetailView):
    def get(self, request, *args, **kwargs):
        try:
            return super().get(request, *args, **kwargs)
        except Http404:
            return redirect(reverse('my_list_view_name'))

2👍

You should redefine def get_object(self): of the DetailView

There’s something similar in this question

👤msc

Leave a comment