限制(许可)Django 员工用户更改模型的某些字段
Restrict (permission) Django staff user from changing certain fields of a model
假设我有一个博客模型
class Blog(models.Model):
author = models.ForeignKey(User)
title = models.CharField(max_length=250, unique=True)
body = models.TextField()
我有一个模型管理员,它确保哪个用户可以更改哪个博客:
class BlogAdmin(admin.ModelAdmin):
def has_add_permission(self, request):
return request.user.groups.filter(name='author').exists()
def has_change_permission(self, request, obj=None):
return request.user.groups.filter(name='editor').exists() or (request.user.groups.filter(name='author').exists() and Blog.objects.filter(pk=obj, author=request.user).count() >0 )
def has_delete_permission(self, request, obj=None):
return request.user.groups.filter(name='editor').exists() or (request.user.groups.filter(name='author').exists() and Blog.objects.filter(pk=obj, author=request.user).count() >0 )
但是我想限制一组用户更改博客模型的字段,比如'author'组不能通过管理面板更改作者的字段。
我该怎么做?提前致谢。
我想我找到了方法。我可以覆盖 ModelAdmin
的 save_model
方法并执行以下操作...
class ArticleAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if request.user in permited user:
obj.save()
else:
raise forms.ValidationError("you can't do that.")
假设我有一个博客模型
class Blog(models.Model):
author = models.ForeignKey(User)
title = models.CharField(max_length=250, unique=True)
body = models.TextField()
我有一个模型管理员,它确保哪个用户可以更改哪个博客:
class BlogAdmin(admin.ModelAdmin):
def has_add_permission(self, request):
return request.user.groups.filter(name='author').exists()
def has_change_permission(self, request, obj=None):
return request.user.groups.filter(name='editor').exists() or (request.user.groups.filter(name='author').exists() and Blog.objects.filter(pk=obj, author=request.user).count() >0 )
def has_delete_permission(self, request, obj=None):
return request.user.groups.filter(name='editor').exists() or (request.user.groups.filter(name='author').exists() and Blog.objects.filter(pk=obj, author=request.user).count() >0 )
但是我想限制一组用户更改博客模型的字段,比如'author'组不能通过管理面板更改作者的字段。
我该怎么做?提前致谢。
我想我找到了方法。我可以覆盖 ModelAdmin
的 save_model
方法并执行以下操作...
class ArticleAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if request.user in permited user:
obj.save()
else:
raise forms.ValidationError("you can't do that.")