Skip to content

Instantly share code, notes, and snippets.

@rg3915
Created August 31, 2023 11:52
Show Gist options
  • Save rg3915/c31b5a12bc6c46ed339916c5bfc7d9ad to your computer and use it in GitHub Desktop.
Save rg3915/c31b5a12bc6c46ed339916c5bfc7d9ad to your computer and use it in GitHub Desktop.
redirect with LoginRequiredMixin
from django.contrib.auth.mixins import LoginRequiredMixin as LRM
from django.contrib.auth.mixins import PermissionRequiredMixin as PRM
class CustomPRMMixin(PRM):
def handle_no_permission(self):
if self.raise_exception: # or self.request.user.is_authenticated:
raise PermissionDenied(self.get_permission_denied_message())
if self.request.user.is_authenticated:
return redirect('core:dashboard')
path = self.request.build_absolute_uri()
resolved_login_url = resolve_url(self.get_login_url())
# If the login url is the same scheme and net location then use the
# path as the "next" url.
login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
current_scheme, current_netloc = urlparse(path)[:2]
if (not login_scheme or login_scheme == current_scheme) and (
not login_netloc or login_netloc == current_netloc
):
path = self.request.get_full_path()
return redirect_to_login(
path,
resolved_login_url,
self.get_redirect_field_name(),
)
class ProdutoCreateView(LRM, CustomPRMMixin, CreateView):
model = Produto
form_class = ProdutoForm
permission_required = 'produto.add_produto'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment