django create user with permissions code example
Example 1: django user permission check
...
class BlogPost(models.Model):
...
class Meta:
permissions = [('can_write_blog', 'Can Write Blog')]
if request.user.has_perm('app_name.can_write_blog'):
else:
Example 2: Django: checking permission on user
from typing import Set
from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
@admin.register(User)
class CustomUserAdmin(UserAdmin):
def get_form(self, request, obj=None, **kwargs):
form = super().get_form(request, obj, **kwargs)
is_superuser = request.user.is_superuser
disabled_fields = set()
if not is_superuser:
disabled_fields |= {
'username',
'is_superuser',
'user_permissions',
}
for f in disabled_fields:
if f in form.base_fields:
form.base_fields[f].disabled = True
return form