6

このチュートリアルに従う:

http://django-rest-framework.org/tutorial/1-serialization.html

http://django-rest-framework.org/tutorial/4-authentication-and-permissions.htmlから

私はこのコードを持っています:

# models.py
class Message(BaseDate):
    """
    Private Message Model
    Handles private messages between users
    """
    status = models.SmallIntegerField(_('status'), choices=choicify(MESSAGE_STATUS))
    from_user = models.ForeignKey(User, verbose_name=_('from'), related_name='messages_sent')
    to_user = models.ForeignKey(User, verbose_name=_('to'), related_name='messages_received')
    text = models.TextField(_('text'))
    viewed_on = models.DateTimeField(_('viewed on'), blank=True, null=True)


# serialisers.py
class MessageSerializer(serializers.ModelSerializer):
    from_user = serializers.Field(source='from_user.username')
    to_user = serializers.Field(source='to_user.username')

    class Meta:
        model = Message
        fields = ('id', 'status', 'from_user', 'to_user', 'text', 'viewed_on')


# views.py
from permissions import IsOwner

class MessageDetail(generics.RetrieveUpdateDestroyAPIView):
    model = Message
    serializer_class = MessageSerializer
    authentication_classes = (TokenAuthentication, SessionAuthentication)
    permission_classes = (permissions.IsAuthenticated, IsOwner)


# permissions.py
class IsOwner(permissions.BasePermission):
    """
    Custom permission to only allow owners of an object to edit or delete it.
    """

    def has_permission(self, request, view, obj=None):
        # Write permissions are only allowed to the owner of the snippet
        return obj.from_user == request.user


# urls.py
urlpatterns = patterns('',
    url(r'^messages/(?P<pk>[0-9]+)/$', MessageDetail.as_view(), name='api_message_detail'),
)

次に、APIのURLを開くと、次のエラーが発生します。

**AttributeError at /api/v1/messages/1/
'NoneType' object has no attribute 'from_user'**

Traceback:
File "/var/www/sharigo/python/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/var/www/sharigo/python/lib/python2.6/site-packages/django/views/generic/base.py" in view
  48.             return self.dispatch(request, *args, **kwargs)
File "/var/www/sharigo/python/lib/python2.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
  77.         return view_func(*args, **kwargs)
File "/var/www/sharigo/python/lib/python2.6/site-packages/rest_framework/views.py" in dispatch
  363.             response = self.handle_exception(exc)
File "/var/www/sharigo/python/lib/python2.6/site-packages/rest_framework/views.py" in dispatch
  351.             self.initial(request, *args, **kwargs)
File "/var/www/sharigo/python/lib/python2.6/site-packages/rest_framework/views.py" in initial
  287.         if not self.has_permission(request):
File "/var/www/sharigo/python/lib/python2.6/site-packages/rest_framework/views.py" in has_permission
  254.             if not permission.has_permission(request, self, obj):
File "/var/www/sharigo/sharigo/apps/sociable/permissions.py" in has_permission
  17.         return obj.from_user == request.user

Exception Type: AttributeError at /api/v1/messages/1/
Exception Value: 'NoneType' object has no attribute 'from_user'

パラメータ「obj」の値としてisOwner.has_permission()にNoneが渡されているようです。私は何が間違っているのですか?私は厳密にチュートリアルに従ったと思います。

4

2 に答える 2

9

has_permission()で呼び出されると、ユーザーがこのタイプオブジェクトに対するobj=Noneアクセス許可を持っているかどうかを返すことになっています。したがって、Noneが渡された場合に対処する必要があります。

コードは次のようになります。

def has_permission(self, request, view, obj=None):
    # Write permissions are only allowed to the owner of the snippet
    return obj is None or obj.from_user == request.user
于 2013-01-13T08:42:10.440 に答える
9

has_object_permissionの代わりに関数を使用してくださいhas_permission

元:

def has_object_permission(self, request, view, obj=None):
    return obj.from_user == request.user

check_object_permissionsビューのget_object内で関数を呼び出します

def get_object(self):
    obj = get_object_or_404(self.get_queryset())
    self.check_object_permissions(self.request, obj)
    return obj
于 2014-06-02T11:03:16.177 に答える