我的想象是一个非常常见的情况,但我在搜索中没有找到任何明确的解决方案。
我有一个网络应用程序,其中大多数对象与用户具有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
答案 0 :(得分:3)
我认为你的代码是正确的,但是没有必要复制所有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