我有一个部门表。以及引用department表的 Student 表。我还创建了一个自定义用户模型 UserAugment ,将部门字段添加到默认的用户模型。
class Department(models.Model):
dname = models.CharField(max_length=200,primary_key=True)
def publish(self):
self.save()
def __str__(self):
return self.dname
class UserAugment(AbstractUser):
department = models.ForeignKey(Department,null=True,blank=True)
objects = UserManager()
class Student(models.Model):
sname = models.CharField(max_length=200)
usn = models.CharField(max_length=200,primary_key=True)
dept = models.ForeignKey(Department)
sem = models.IntegerField()
def publish(self):
self.save()
def __str__(self):
return '%s, %s' % (self.usn,self.sname)
现在,我需要创建将附加部门的用户。每个用户都应获得为其所属部门的学生添加/编辑/查看的权限。我做了一个噩梦。真的很简单吗?感谢您提出的任何帮助。
答案 0 :(得分:0)
您可以在管理员中管理权限控制:
class UserAdmin(admin.ModelAdmin):
def has_change_permission(self, request, obj=None):
return self.user_has_permission(request, obj)
def user_has_permission(self, request, obj):
if hasattr(request.user, 'department') and obj is not None:
return request.user.department == obj.dept
return False
您可以采用相同的方式实现edit
和delete
权限。
答案 1 :(得分:0)
嗯,这最终对我有用,
class StudentAdmin(admin.ModelAdmin):
def get_queryset(self, request):
qs = super(StudentAdmin, self).get_queryset(request)
if request.user.is_superuser:
return qs
return qs.filter(dept=request.user.department)