我在models.py中有一个布尔字段,称为“状态”,管理员只能对其进行修改,因为它是一个布尔字段。现在,我希望某些用户专门编辑该字段,而所有其他字段都必须是只读的。在django-admin界面中,用户权限可以完全编辑或只读。
我如何实现我的目标?
顺便说一句,这是一个请假管理系统项目
#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)
accepted = models.BooleanField(('status'), default=False)
def __str__(self):
return self.name
我是新的Django和stackoverflow。请指出我在提问时是否需要更多/更少的描述。谢谢。
更新***
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,
)
现在,在我的views.py中提供代号和名称之后,我应该在哪里指定用户有权编辑的字段?该权限已反映在“管理员用户权限”面板中,但该功能未实现。
答案 0 :(得分:0)
首先添加渗透,如下所示:
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,
)
,然后在创建用户时要使用权限,如下所示:
user = User.objects.create(...)
permission = Permission.objects.get(codename='can_change_status')
user.user_permissions.add(permission)
然后检查用户是否有权更改状态:
return request.user.has_perm('app.can_change_status')
'''This will return `True` if the user has the 'Change Status' permission
'''
进一步了解Django Docs v2 Here