Custom Decorators To Check User Roles And Permissions In Django

from django.contrib.auth.decorators import login_required@login_required(login_url='/dashboard/')def index(request):    return render(request, 'index.html')
from django.contrib.auth.decorators import login_required, user_passes_testuser_login_required = user_passes_test(lambda user: user.is_active, login_url='/')def active_user_required(view_func):
decorated_view_func = login_required(user_login_required(view_func))
return decorated_view_func
@active_user_required
def index(request):
return render(request, 'index.html')
def is_recruiter(self):
if str(self.user_type) == 'Recruiter':
return True
else:
return False
rec_login_required = user_passes_test(lambda u: True if u.is_recruiter else False, login_url='/')
def recruiter_login_required(view_func):
decorated_view_func = login_required(rec_login_required(view_func), login_url='/')
return decorated_view_func
@recruiter_login_required
def index(request):
return render(request, 'index.html')
class Meta:
permissions = (
('blog_view', 'can view blog posts and categories'),
('blog_edit', 'can edit blog category and post'),
("support_view", "can view tickets"),
("support_edit", "can edit tickets"),
("activity_view", "can view recruiters, applicants, data, posts"),
("activity_edit", "can edit data"),
)
def has_perm(self, perm, obj=None):
try:
user_perm = self.user_permissions.get(codename=perm)
except ObjectDoesNotExist:
user_perm = False
if user_perm:
return True
else:
return False
def permission_required(*perms):
return user_passes_test(lambda u: any(u.has_perm(perm) for perm in perms), login_url='/')
@permission_required("activity_view", "activity_edit")
def index(request):
return render(request, 'index.html')

The article was originally published at MicroPyramid blog.

--

--

--

Python, Django, Android and IOS, reactjs, react-native, AWS, Salesforce consulting & development company

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Flask for (absolute) Beginners !

Flask, web development, one drop at a time!

Configuring Apache Webserver & Python on Docker Container

R Flow Control — 2

Using Blender to run Python and visualizing Fourier Series

Updating a Proxmox Cluster from 4.4 to 5.4 the safe way

A Simple Bucket Policy Trick for AWS S3 Buckets; Deny All, Except One Federated User

Network Fundamentals — Part 2

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
MicroPyramid

MicroPyramid

Python, Django, Android and IOS, reactjs, react-native, AWS, Salesforce consulting & development company

More from Medium

Optimize query size in Django

Expenses Tracker App using Django and Pandas.