python 3.x - How can I make a specific login for specific group with Django's `authenticate()`? -
hello have been looking through documentation in https://docs.djangoproject.com/en/1.11/topics/auth/default/#authenticating-users. however, shows how authenticate user
.
i have grouped user
want specific user
login in specific form. how can achieve that?
additionally, when should use permissions
, when should use groups
?
i suggest create custom decorator it, why? because think method easy understand how work group using permissions.
an example in yourapp/decorators.py
:
you can see, here focusing on
if ... request.user.groups.filter(name='moderator')
handle group.
from django.shortcuts import render def moderator_login_required(function): def wrap(request, *args, **kwargs): if request.user.is_authenticated() \ , request.user.groups.filter(name='moderator').exists(): return function(request, *args, **kwargs) else: context = { 'title': _('403 forbidden'), 'message': _('you not allowed access page!') } # can return redirect page here. return render(request, 'path/to/error_page.html', context) wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap
ho use in views.py
?
from yourapp.decorators import moderator_login_required @moderator_login_required def dashboard(request): #do_stuff
or, if working cbv (class bassed view), can using @method_decorator
, eg:
from django.views.generic.base import templateview django.utils.decorators import method_decorator yourapp.decorators import moderator_login_required class dashboardview(templateview): @method_decorator(moderator_login_required) def dispatch(self, *args, **kwargs): return super(dashboardview, self).dispatch(*args, **kwargs)
hope helpful..
Comments
Post a Comment