本文介绍了如何在不定义内容类型或模型的情况下使用Django权限?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用基于权限的系统来限制Django应用程序中的某些操作.这些操作不必与特定模型相关(例如,访问应用程序中的各个部分,进行搜索...),因此我不能使用,因为模型需要引用已安装的内容类型.

I'd like to use a permissions based system to restrict certain actions within my Django application. These actions need not be related to a particular model (e.g. access to sections in the application, searching...), so I can't use the stock permissions framework directly, because the Permission model requires a reference to an installed content type.

我可以编写自己的权限模型,但随后必须重写Django权限随附的所有功能,例如:

I could write my own permission model but then I'd have to rewrite all the goodies included with the Django permissions, such as:

  • The possibility to assign permissions to users and groups.
  • The permission_required decorator.
  • User.has_perm and related user methods.
  • The perms template variable.
  • ...

我已经检查了一些应用程序,例如 django-authority 和,但是它们似乎通过允许每个对象的权限来提供与模型系统更紧密相关的权限.

I've checked some apps like django-authority and django-guardian, but they seem to provide permissions even more coupled to the model system, by allowing per-object permissions.

是否有一种方法可以重用此框架而无需为项目定义任何模型(除了UserGroup)?

Is there a way to reuse this framework without having defined any model (besides User and Group) for the project?

推荐答案

Django的Permission模型需要一个ContentType实例.

Django's Permission model requires a ContentType instance.

我认为一种解决方法是创建一个与任何模型都不相关的虚拟ContentType(app_labelmodel字段可以设置为任何字符串值).

I think one way around it is creating a dummy ContentType that isn't related to any model (the app_label and model fields can be set to any string value).

如果您希望它们整洁美观,则可以创建Permission 代理模型,用于处理虚拟ContentType的所有丑陋细节,并创建无模型"权限实例.您还可以添加一个自定义管理器,以过滤掉与真实模型相关的所有Permission实例.

If you want it all clean and nice, you can create a Permission proxy model that handles all the ugly details of the dummy ContentType and creates "modelless" permission instances. You can also add a custom manager that filters out all Permission instances related to real models.

这篇关于如何在不定义内容类型或模型的情况下使用Django权限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 04:43