Skip to content

Instantly share code, notes, and snippets.

@canokay
Last active May 29, 2022 17:44
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save canokay/7c76e38b1c403f24768583e49d22871c to your computer and use it in GitHub Desktop.
Save canokay/7c76e38b1c403f24768583e49d22871c to your computer and use it in GitHub Desktop.
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
Copy link
Author

canokay commented Dec 23, 2018

@allexiusw
Copy link

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