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'))
- How to add some extra fields to the page in django-cms? (in django admin panel)
- Django: passing JSON from view to template
2👍
You should redefine def get_object(self):
of the DetailView
There’s something similar in this question
👤msc
- Django Check and set permissions for a user group
- Django 1.7 and connection pooling to PostgreSQL?
- Django extract string from [ErrorDetail(string='Test Message', code='invalid')]
- Django admin – select reverse foreign key relationships (not create, I want to add available)
Source:stackexchange.com