如果在基于 class 的视图 Django 中发生错误,如何重定向

How to redirect if error occurs inside class-based view Django

我有一个基于 class 的视图(可以说是 DetailView),它根据 URL 中的 slug 呈现一个包含对象列表的页面。但是,如果不存在具有给定 slug 的对象,则会给我一个错误。我想要的是重定向到主页而不是引发错误。这应该很容易,但我不明白如何做到这一点,所以我想在这里寻求帮助。

简单地说,我想找到类似“success_url”的内容,但有错误。

示例:

views.py

class ShowExerciseRecords(ListView):
   def get_queryset(self):
      exercise = Exercise.objects.get(slug=self.kwargs['slug'])
      return exercise.record__set.all()

urls.py

urlpatterns = [
   path('/exercise/<slug:slug>/', ShowExerciseRecords.as_view())
   path('', index, name='home') 
]

请试试这个代码,

class ShowExerciseRecords(ListView):
    def get_queryset(self):
        records = Record.objects.none() # you should replace the exact model name 
        exercise = Exercise.objects.filter(slug=self.kwargs['slug']).first() 
        if exercise:
            records = exercise.record__set.all()
        return records

    def get(self, request, *args, **kwargs):
        self.object_list = self.get_queryset() 
        if self.object_list:
            context = self.get_context_data()
            return self.render_to_response(context)
        return redirect("main-page-url") # you should change the url to your case 

你可以使用 try 除了例如:

try:
    Exercise.objects.get(slug=self.kwargs['slug'])
except Exercise.DoesNotExist:
    redirect("main-page-url")