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

Time:03-30

I have a class-based view (lets say, DetailView) which renders a page with a list of objects based on slug in the URL. But if an object with the given slug does not exist, it gives me an error. What I want is to redirect to the main page instead of raising an error. It should be easy, but I can't understand how to do this, so I wanna ask for help here.

Simply, I wanna find something like "success_url" but for errors.

Example:

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') 
]

CodePudding user response:

please try this code,

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 

CodePudding user response:

you can use try except for example:

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