I am trying to restrict instances of an object to be viewable only to users referenced by that object via a OneToOneField. I'm using the “user_passes_test” mixin on a DetailView to compare request.user to the user in the OnetoOne relationship. 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).
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)
If you are using DetailView
then you can implement the get_queryset
method in the view:
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.
I am not sure what URL are you using to access the Event and why there is just OneToOne
relation between Event
and User
. But if it is a OneToOne
relation then the queryset
after this implementation will contain only one object. (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:
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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.