Created
March 9, 2018 05:07
-
-
Save safu9/01f6157711d681b7eedce8619abe1719 to your computer and use it in GitHub Desktop.
Django Mixin for Redirect
This file contains hidden or 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.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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
from django.core.exceptions import ImproperlyConfigured