如何创建自定义用户权限?

时间:2018-08-17 06:55:47

标签: python django user-permissions

我有一个模型表格,该表格用于从员工角度请求请假。我希望另一个用户接受或拒绝休假,为此,我有一个专用的布尔字段。

models.py

from django.db import models
from django.contrib.auth.models import User

CHOICES = (('1','Earned Leave'),('2','Casual Leave'),('3','Sick Leave'),('4','Paid Leave'))

class Leave(models.Model):

    name = models.CharField(max_length = 50)
    user = models.ForeignKey(User, on_delete = models.CASCADE, null =True)
    employee_ID = models.CharField(max_length = 20)
    department = models.CharField(max_length = 15)
    designation = models.CharField(max_length = 15)
    type_of_leave = models.CharField(max_length = 15, choices = CHOICES, default = None)
    from_date = models.DateField()
    to_date = models.DateField()
    reporting_manager = models.CharField(max_length = 50, default = None)
    reason = models.CharField(max_length= 180)
    permission = models.BooleanField(('status'), default=False)


def __str__(self):
    return self.name

现在,我的目标是进行自定义权限,以便其他用户可以只读除“ permission”字段之外的其余字段,在该字段中,他可以接受或拒绝。 我尝试使用以编程方式创建的用户权限,该用户权限反映在“用户权限面板”中,但未达到我想要的功能。

views.py

from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from .models import Leave


content_type = ContentType.objects.get_for_model(Leave)
permission = Permission.objects.create(
   codename='can_change_status',
   name='Can Change Status',
   content_type=content_type,
)

谢谢,请帮助我完成我的项目。

1 个答案:

答案 0 :(得分:0)

def get_readonly_fields(self, request, obj=None):     
        if obj and request.user.is_staff:
            readonly_fields = [f.name for f in self.opts.fields]
            readonly_fields.remove('permission')    
        return readonly_fields

将此添加到您的admin.py中,类为....(ModelAdmin)