Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Django Custom View Decorators
from django.http import HttpResponseRedirect
from django.core.exceptions import PermissionDenied
from django.urls import reverse
from django.shortcuts import render
from django.shortcuts import redirect
def role_required(allowed_roles=[]):
def decorator(view_func):
def wrap(request, *args, **kwargs):
if request.user.profile.userStatus in allowed_roles:
return view_func(request, *args, **kwargs)
else:
return render(request, "dashboard/404.html")
return wrap
return decorator
def admin_only(view_func):
def wrap(request, *args, **kwargs):
if request.user.profile.userStatus == "admin":
return view_func(request, *args, **kwargs)
else:
return render(request, "dashboard/404.html")
return wrap
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(
User, on_delete=models.CASCADE, verbose_name="Username")
userStatus = models.ForeignKey(
'CustomUsers.UserStatus', on_delete=models.CASCADE, verbose_name='User Status')
def __str__(self):
return f'{self.user.username} Profile'
class Meta:
verbose_name = 'User Detail'
verbose_name_plural = 'User Details'
class UserStatus(models.Model):
userStatus = models.CharField(max_length=40, verbose_name="User Status")
class Meta:
verbose_name = 'User Status'
verbose_name_plural = 'User Statuses'
def __str__(self):
return self.userStatus
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.decorators import login_required
from DjangoCustomUsers.decorators import admin_only, role_required
@login_required(login_url="login")
@admin_only
def JustAdminView(request):
return render(request, 'justAdmin.html')
@login_required(login_url="login")
@role_required(allowed_roles=[2])
def JustEditorView(request):
return render(request, 'justEditor.html')
@login_required(login_url="login")
@role_required(allowed_roles=[1, 2])
def AdminOrEditorView(request):
return render(request, 'adminOrEditor.html')
@canokay

This comment has been minimized.

Copy link
Owner Author

@canokay canokay commented Dec 23, 2018

@allexiusw

This comment has been minimized.

Copy link

@allexiusw allexiusw commented Feb 2, 2021

Really helpfull example to work custom permissions... Thanks a lot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment