How do I redirect from a Django DetailView when the specified object doesn't exist?
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)
You should redefine def get_object(self):
of the DetailView
There's something similar in this question