gpt4 book ai didi

Django 基于类的 View : How to check an object value before returning view

转载 作者:行者123 更新时间:2023-12-04 05:31:52 29 4
gpt4 key购买 nike

我有我想象的一个很常见的场景,但我在搜索中没有找到任何明确的解决方案。

我有一个 Web 应用程序,其中大多数对象与用户具有 FK 关系。对于这些对象,我想检查相关用户是否与 self.request.user 相同。

我写了一个 mixin 来覆盖 get_object 以在返回对象之前执行这个简单的检查。

有更好的方法吗?在这里我只是举个例子,404。我可能会在实际代码中为此返回一条专门的消息。

class CheckObjectUserMixin(object):
def get_object(self, queryset=None):
if queryset is None:
queryset = self.get_queryset()

pk = self.kwargs.get(self.pk_url_kwarg, None)
slug = self.kwargs.get(self.slug_url_kwarg, None)
if pk is not None:
queryset = queryset.filter(pk=pk)

elif slug is not None:
slug_field = self.get_slug_field()
queryset = queryset.filter(**{slug_field: slug})

else:
raise AttributeError(u"Generic detail view %s must be called with "
u"either an object pk or a slug."
% self.__class__.__name__)

try:
obj = queryset.get()
except ObjectDoesNotExist:
raise Http404(_(u"No %(verbose_name)s found matching the query") %
{'verbose_name': queryset.model._meta.verbose_name})

# Until here it was the code from Django's get_object.
# Now for the CheckObjectUserMixin I perform a simple check.
# If the object does not belong to the request user, we want to raise an 404.

if obj.user_id != self.request.user.id:
raise Http404(_(u'You do not have permission to view this page'))
else:
return obj

最佳答案

我认为你的代码是正确的,但没有必要复制所有 Django 的 get_object代码。
相反,您可以这样做:

from django.views.generic.detail import SingleObjectMixin

class CheckObjectUserMixin(SingleObjectMixin):
def get_object(self, queryset=None):
obj = super(CheckObjectUserMixin, self).get_object(queryset)
if obj.user_id != self.request.user.id:
raise Http404
return obj

关于Django 基于类的 View : How to check an object value before returning view,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12472290/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com