django: How to redirect from DetailView when the specified object does not exist?

created at 07-15-2021 views: 2

Introduction

Use the get_object method of DetailView to trigger Http404, if the object does not exist in the query set, there is an exception. In addition to overriding the get_object method, you can also catch exceptions in the get method of the view:

Solutions

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)

or

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'))
Please log in to leave a comment.