I'm trying to instead use the Class based view, and all I end up with the default 403 Forbidden page.. Is the order of the mixin classes correct? Does the code even get used -as in get/post or does everything get bypassed and the default 403 redirect occur?
All working examples seen so far, only point to the decorator @login_required in a function based view and use the request object to redirect to the login page. The documentation provides some tips, but I can't get it to work with the code below.. Putting the error stack as well.
check
"GET / HTTP/1.1" 200 2580
Forbidden (Permission denied): /app/custom-view
Traceback (most recent call last):
File "C:\Users\me\.envs\project\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\me\.envs\project\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\me\.envs\project\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\me\.envs\project\lib\site-packages\django\views\generic\base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\me\.envs\project\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch
return super().dispatch(request, *args, **kwargs)
File "C:\Users\me\.envs\project\lib\site-packages\django\contrib\auth\mixins.py", line 108, in dispatch
return self.handle_no_permission()
File "C:\Users\me\.envs\project\lib\site-packages\django\contrib\auth\mixins.py", line 43, in handle_no_permission
raise PermissionDenied(self.get_permission_denied_message())
django.core.exceptions.PermissionDenied
Code:
class UserIsAdminMixin(UserPassesTestMixin):
def test_func(self):
return request.user.groups.filter(name='CustomAdmin').exists()
class CustomAdminView(LoginRequiredMixin, UserIsAdminMixin, TemplateView):
template_name = 'template.html'
# login_url = '/login/'
# redirect_field_name = 'my_link_name'
def get(self, request):
form = CustomForm()
# This does not work neither does setting up login_url
if not request.user.is_authenticated or not request.user.is_staff or not self.request.user.groups.filter(name='CustomAdmin').exists():
return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
I am willing to trying out this solution, if the above approach doesn't work
According to this answer, you can use handle_no_permission(self):
to handle the redirect URL.
Simply:
def handle_no_permission(self):
return redirect('users:create-profile')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With