简体   繁体   English

如何为 django 管理站点创建自定义权限

[英]How to create custom permissions for django admin site

By default when I create a model Django gives permissions like默认情况下,当我创建模型时,Django 会授予类似的权限

add/change/delete/view 

If I give any of the above permission to a specific user then that user can view all the objects from that model.如果我将上述任何权限授予特定用户,则该用户可以查看该模型中的所有对象。 But I want to show them only objects linked with foreign keys.但我只想向他们展示与外键链接的对象。

Let's Say,让我们说,

I have a Book model我有一个 Book 模型

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(
        User, on_delete=models.CASCADE
    )

If I want to give authors permission, they can only view their linked books from the Django admin.如果我想授予作者权限,他们只能从 Django 管理员查看链接的书籍。

How can I do that?我怎样才能做到这一点?

Everything happens in the Django Meta class.一切都发生在 Django Meta 类中。 Just follow what the Django Documantation says:只需按照Django 文档中的说明进行操作即可:

class Meta:
        permissions = [
            ("change_task_status", "Can change the status of tasks"),
            ("close_task", "Can remove a task by setting its status as closed"),
        ]

If you want to manipulate the default permission, you follow these documentation explanation an add this to you model.如果您想操作默认权限,请按照这些文档说明将其添加到您的模型中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM