简体   繁体   English

Django-将相关对象作为变量传递给user_passes_test mixin

[英]Django - Pass related object as variable in user_passes_test mixin

I am trying to restrict instances of an object to be viewable only to users referenced by that object via a OneToOneField. 我试图将对象的实例限制为只能由该对象通过OneToOneField引用的用户查看。 I'm using the “user_passes_test” mixin on a DetailView to compare request.user to the user in the OnetoOne relationship. 我在DetailView上使用“ user_passes_test”混合输入来将request.user与OnetoOne关系中的用户进行比较。 I got some help on django irc which led me to unsuccessfully try and implement get_object, but I'm still stuck (I'm new to Django & Python). 我在django irc上获得了一些帮助,这使我未能成功尝试实现get_object,但是我仍然受困(我是Django&Python的新手)。

the Model: 该模型:

class Event(models.Model):     
    client = models.OneToOneField(settings.AUTH_USER_MODEL)

the View: 风景:

class EventDetail(UserPassesTestMixin, DetailView):
    model = Event

    def test_func(self):
        if self.request.user == self.model.client:
            return True
        else:
            return False

User is being referenced in its own app, as User(AbstractUser) 用户在自己的应用中被引用为User(AbstractUser)

If you are using DetailView then you can implement the get_queryset method in the view: 如果使用的是DetailView则可以在视图中实现get_queryset方法:

class EventDetail(DetailView):
    model = Event

    def get_queryset(self):
        queryset = super(DetalView, self).get_queryset()
        return queryset.filter(client=self.request.user)

This would make sure that the Event objects are restricted to the user as a client only. 这样可以确保将Event对象限制为仅作为客户端的用户。

I am not sure what URL are you using to access the Event and why there is just OneToOne relation between Event and User . 我不确定您使用什么URL来访问Event以及为什么EventUser之间只有OneToOne关系。 But if it is a OneToOne relation then the queryset after this implementation will contain only one object. 但是,如果它是一个OneToOne关系,则此实现后的queryset将仅包含一个对象。 (which might or might not be the primary key using which you are accessing this event). (它可能是访问此事件的主键,也可能不是)。

I finally got it, I think it took me writing it out to realize I could just put an if / else condition on the queryset like this: 我终于明白了,我认为花了我的力气才意识到我可以在查询集上设置if / else条件,如下所示:

def get_queryset(self):
    queryset = super(DetailView, self).get_queryset()
    if self.request.user.is_staff:
        return queryset
    else:
        return queryset.filter(client=self.request.user)

Thank you AKS! 谢谢AKS!

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

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