2

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

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

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

有没有更好的办法?在这里,我只是举了 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
4

1 回答 1

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
于 2012-09-18T09:28:47.477 回答