基于 Django 角色的视图? [英] Django role based views?

查看:24
本文介绍了基于 Django 角色的视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找有关其他人如何构建它的一些意见.我将提供基于类(django 组)的视图.

I'm looking for some input on how others would architect this. I'm going to provide class (django group) based views.

例如,用户组将决定他或她可以访问哪些视图/模板.我正在考虑可能在表格中存储查看功能的路径,以确定用户的链接栏将包含哪些内容.还可以存储过滤器规范以确定哪些行将填充这些模板.

For example, a user's group will determine what views/templates he or she will have access to. I'm thinking of perhaps storing paths to view functions in a table to determine what a user's link bar will consist of. Filter specifications can also be stored to determine what rows will fill these templates.

一个很好的例子是医院的护理单位.一个病房的护士不需要看整个医院的病人.他们只需要看他们的病人.同一单位的医生也只需要看那些病人,但他们应该可以使用更多的功能.

A good example is a hospital nursing units. Nurses at one unit need not see the entire hospital's patients. They only need to see their patients. Doctors on the same unit need only to see those patients as well, but they should have access to much greater functionality.

这是通过某些第三方应用程序完成的吗?您将如何解决这个问题?

Has this been done via some third party application? And how would you approach this problem?

谢谢,皮特

推荐答案

Django 已经有一个组和权限系统,这可能足以满足您的目的.

Django already has a groups and permissions system, which may be sufficient for your purpose.

http://docs.djangoproject.com/en/dev/topics/auth/

通常在您的代码中,您会检查用户是否具有权限.用户拥有自己的权限以及他所属组的权限.您可以从管理控制台轻松管理此操作.

Generally in your code you check if a user has a permission. A user has his own permissions and those of the groups he belongs to. You can administer this pretty easily from the admin console.

您需要查看两个部分.

  1. 检查请求页面的用户有权这样做.
  2. 仅当用户显示链接时有权限.

对于 1. 你可以在装饰器中检查权限:

For 1. you can check permissions in a decorator as such:

from django.contrib.auth.decorators import permission_required

@permission_required('polls.can_vote')
def some_view(request):

对于 2. 当前登录用户的权限存储在模板变量 {{ perms }} 中.此代码检查与上述相同的权限.

For 2. the currently logged-in user's permissions are stored in the template variable {{ perms }}. This code checks the same permission as above.

{% if perms.polls.can_vote %}
    <a href="/vote">vote</a>
{% endif %}

要生成链接列表,您可以遍历 user.get_all_permissions() 并从字典中获取链接(或生成链接的函数):

To generate a list of links you can iterate over user.get_all_permissions() and fetch the links (or function that generates the link) from a dict:

def more_elaborate_list_of_links_for_a_perm(user):
    return ["/link1", ...]

_LINKS = {
    'polls.can_vote' : lambda u: ["/user/specific/link/" + u.id],
    'polls.can_close': lambda u: ['/static/link/1', 'static/link/2'],
    'polls.can_open' : more_elaborate_list_of_links_for_a_perm
}

def gen_links(user):
    # get_all_permissions also gets permissions for users groups
    perms = user.get_all_permissions()
    return sum((_LINKS[p](user) for p in perms if p in _LINKS), [])

可能还有许多其他方法.

There are probably many other approaches.

这篇关于基于 Django 角色的视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆