Skip to content

Instantly share code, notes, and snippets.

@safu9
Created March 9, 2018 05:07
Show Gist options
  • Select an option

  • Save safu9/01f6157711d681b7eedce8619abe1719 to your computer and use it in GitHub Desktop.

Select an option

Save safu9/01f6157711d681b7eedce8619abe1719 to your computer and use it in GitHub Desktop.
Django Mixin for Redirect
from django.shortcuts import redirect
class RedirectMixin:
"""
Redirect to redirect_url if the test_func() method returns False.
"""
redirect_url = None
def get_redirect_url(self):
"""
Override this method to override the redirect_url attribute.
"""
redirect_url = self.redirect_url
if not redirect_url:
raise ImproperlyConfigured(
'{0} is missing the redirect_url attribute. Define {0}.redirect_url or override '
'{0}.get_redirect_url().'.format(self.__class__.__name__)
)
return str(redirect_url)
def test_func(self):
raise NotImplementedError(
'{0} is missing the implementation of the test_func() method.'.format(self.__class__.__name__)
)
def get_test_func(self):
"""
Override this method to use a different test_func method.
"""
return self.test_func
def dispatch(self, request, *args, **kwargs):
test_result = self.get_test_func()()
if not test_result:
return redirect(self.get_redirect_url())
return super().dispatch(request, *args, **kwargs)
@astarrh
Copy link

astarrh commented Jun 20, 2019

from django.core.exceptions import ImproperlyConfigured

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment