【问题标题】:Django Application require groupDjango 应用程序需要组
【发布时间】:2013-10-31 09:32:51
【问题描述】:

我为我的 Django 站点编写了一个单独的应用程序,名为 restricted,并驻留在

http://localhost:8000/restricted/

我希望能够将整个应用程序的访问权限限制为仅限特定组的成员(我们称之为“受限组”)。

有没有办法轻松做到这一点?也许在urls.conf 文件中?该应用程序充满了基于类的列表视图(30+),所以我不想将这种检查应用于我的 view.py 文件中的每个视图。

编辑:为了解决这个问题,我在视图中添加了一个函数:

def group_check(user):
    if user:
        return user.groups.filter(name='Restricted').count() >= 1
    return False

对于任何普通视图(如index),我都放了装饰器:

@user_passes_test(group_check)
def index(request):
    return render_to_response('listview/index.html')

对于我的基于类的列表视图:

class MyListView1(ListView):
    context_object_name = "objs"
    queryset = MyList.objects.all()
    template_name = "listviews/mylist.html"

    @method_decorator(user_passes_test(group_check))
    def dispatch(self, *args, **kwargs):
        return super(MyListView1, self).dispatch(*args, **kwargs)

对于那些重新定义查询集的:

class MyListView1_Custom(ListView):
    context_object_name = "obj"
    template_name = "listviews/mylist_custom.html"

    @method_decorator(user_passes_test(group_check))
    def get_queryset(self):
        self.obj1 = get_object_or_404(MyList, id__iexact=self.args[0])
        self.context = {}
        self.context['custom'] = self.obj1
        return self.context

当然,这需要你导入:

from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import user_passes_test

经过测试,我得出结论,这是一种合适的基于组的视图保护方法。任何不属于“受限”组的用户都会被重定向到默认登录页面。

您可以在 Django 的文档页面找到更多信息:user_passes_test,其中还描述了如何将它们重定向到不同的位置(如果您愿意,可以使用它来重定向到 404)。

【问题讨论】:

    标签: django url access-control


    【解决方案1】:

    简而言之 - 你不能在 urls conf 中做。原因很简单。这些文件会在 Django 启动后编译,不会被动态解释。

    相反,您可以构建一个自定义装饰器,例如 restricted_required,类似于 django 提供的 login_required,并在您需要的任何地方使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-18
      • 2010-12-23
      • 2013-12-12
      • 2016-02-01
      相关资源
      最近更新 更多