简体   繁体   English

django 权限的自定义系统

[英]Custom system for permissions with django

I'm looking for a way to make my own system of groups and permissions in Django.我正在寻找一种方法来在 Django 中创建我自己的组和权限系统。 I know that Django by default brings a system of groups and permits, but in my project due to teacher requirements I had to create my own models.我知道 Django 默认带有一个组和许可系统,但在我的项目中,由于教师的要求,我不得不创建自己的模型。

You can create new groups and add permissions to those groups, but since they are not the default models of django I cannot use the template-level functions such as 'perms.car.add_car' for example.您可以创建新组并为这些组添加权限,但由于它们不是 django 的默认模型,因此我无法使用模板级函数,例如“perms.car.add_car”。 What I mean by this?我的意思是什么? That at the template level, I don't know how to validate if the user has the permission.在模板级别,我不知道如何验证用户是否具有权限。 I hope I have explained myself well, I await your answers and thank you in advance!我希望我已经很好地解释了自己,我等待您的回答,并在此先感谢您!

You should be able to access the current user's attributes from templates with {{user.some_attribute}} .您应该能够使用{{user.some_attribute}}从模板访问当前用户的属性。

You can extend the default django.contrib.auth.models.User class with a one-to-one relationship with a CustomUser class you create, and access it from template the way described above, meaning:您可以使用与您创建的CustomUser类的一对一关系扩展默认的django.contrib.auth.models.User类,并按照上述方式从模板访问它,这意味着:

{{ user.one_to_one_custom_user_field.some_attribute }}

For more info about extending User look at the docs .有关扩展User更多信息,请查看文档

In this CustomUser class add as you see fit:在这个CustomUser类中添加你认为合适的:

  • functions for interacting with the user group classes you created and verifying whether current user is in them or not, or has the right permissions用于与您创建的用户组类交互并验证当前用户是否在其中或是否具有正确权限的功能
  • flag variables (or any other indicative attribute) to indicate the user's groups and permissions.标志变量(或任何其他指示性属性)以指示用户的组和权限。

Use one of these options as the some_attribute accessible from template.使用这些选项之一作为可从模板访问的some_attribute

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

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