在Django中根据用户过滤内容 [英] Filtering content based on users in django

查看:69
本文介绍了在Django中根据用户过滤内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户登录时,他/她应该只能看到相应用户创建的对象.

When a user logs in , he/she should be able to see only the objects created by the corresponding users.

我如何在Django中实现这一目标?

How do i achieve this in django?

当我从数据库访问对象时,我是否还应该根据用户的请求对这些对象进行过滤,或者是否有 django 的方式呢?

When i access the objects from the db, should i also do a filter on these objects based on user requesting for it, or is there a django way of doing this ?

推荐答案

这是一个常见要求-我写了一篇有关该主题的博客文章:

This is a common requirement - I've written a blog post about that: http://spapas.github.io/2013/11/05/django-authoritiy-data/ but instead of users having access to their objects, users have access to the objects of their "authority" (i.e group of users belonging to same department, company etc).

无论如何,对于所有只需要创建模型的用户可见/可编辑的模型,都需要向创建模型的用户添加一个名为 created_by 的外键字段.该模型的对象,例如: created_by = models.ForeignKey(settings.AUTH_USER_MODEL,blank = True,null = True)

In any case, for all your models that you need to be visible/editable only by the users that created them, you need to add a foreign key field named created_by with the user that created the object to that model, something like: created_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True)

此后,在创建对象时,您必须使用当前用户更新该字段.例如,如果您使用CBV,则可以使用以下mixin来填充 created_by 字段(摘自我写过的另一篇有关模型审核的博客文章@

After that, when creating the object you'll have to update that field with the current user. For instance, if you use CBVs you can use the following mixin to fill the created_by field (taken from another blog post I've written about auditing for models @ http://spapas.github.io/2015/01/21/django-model-auditing/):


  class AuditableMixin(object,):
    def form_valid(self, form, ):
        if not form.instance.created_by:
            form.instance.created_by = self.request.user

        return super(AuditableMixin, self).form_valid(form)

此后,在显示/更新其他对象列表时(通过ListView,UpdateView,DetailView),您可以覆盖get_queryset方法,以便它仅对具有类似于当前用户创建的结果的结果进行过滤.像这样:

After that, when displaying/updating a list of othese objects (through ListView, UpdateView, DetailView) you can override the get_queryset method so that it will filter only on the results having a created by similar to the current user. Something like this:


  class OnlyMineMixin(object, ):
    def get_queryset(self):
        qs = super(OnlyMineMixin, self).get_queryset()
        return qs.filter(created_by=self.request.user)

现在,所有使用此混合器的CBV将仅 有权访问属于当前用户的对象.

Now all CBVs that use this mixin will only have access to objects belonging to the current user.

这篇关于在Django中根据用户过滤内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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