我正在尝试建立一个频道。我不希望其他用户有权访问详细视图。问题是我可以让一个人可以访问它,但我不知道如何让消费者和卖家都可以访问它?class Group(models.Model): consumer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="", blank=True, null=True) name = models.CharField(max_length=10) seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="") ... def __str__(self): return self.name#Detail channel@method_decorator(login_required(login_url='/cooker/login'),name="dispatch")class CheckoutDetail(generic.DetailView): ... def get(self,request,*args,**kwargs): self.object = self.get_object() if self.object.consumer or self.object.seller != request.user: #it's redirect me to home page return HttpResponseRedirect('/') return super(CheckoutDetail, self).get(request,*args,**kwargs)
2 回答
FFIVE
TA贡献1797条经验 获得超6个赞
正确的逻辑是
if not (request.user == self.object.consumer or request.user == self.object.seller):
return redirect(...)
但我会将该逻辑重构为 中的函数object,例如
def has_access(self, user):
return (self.consumer == user or self.seller == user)
然后调用它,例如
if not self.object.has_access(user=request.user):
# ...
哈士奇WWW
TA贡献1799条经验 获得超6个赞
如果我正确理解你的意思,你必须像这样改变这一行:
if self.object.consumer != request.user and self.object.seller != request.user: return HttpResponseRedirect('/')
添加回答
举报
0/150
提交
取消