Created
March 24, 2023 17:00
-
-
Save chrisgrande/a717a2798b2246623c4934eb513e669d to your computer and use it in GitHub Desktop.
Django view mixin to redirect to a named view on 404
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.http import Http404 | |
from django.urls import reverse | |
from django.shortcuts import redirect | |
from django.views.generic.detail import SingleObjectMixin | |
class RedirectOn404Mixin(SingleObjectMixin): | |
redirect_url_name = None | |
def get(self, request, *args, **kwargs): | |
try: | |
return super().get(request, *args, **kwargs) | |
except Http404: | |
if self.redirect_url_name: | |
redirect_url = reverse(self.redirect_url_name) | |
return redirect(redirect_url) | |
else: | |
raise |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from mixins import RedirectOn404Mixin | |
from django.views.generic import DetailView | |
class TestDetail(RedirectOn404Mixin, DetailView): | |
model = Test | |
redirect_url_name = 'test-index' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment