对象没有属性'build_absolute_uri' - Django Rest Framework

Posted

技术标签:

【中文标题】对象没有属性\'build_absolute_uri\' - Django Rest Framework【英文标题】:object has no attribute 'build_absolute_uri' - Django Rest Framework对象没有属性'build_absolute_uri' - Django Rest Framework 【发布时间】:2015-10-15 08:28:25 【问题描述】:

我正在尝试在我的 api 中查看一个 url(使用 Django Rest Framework),但我收到以下错误:

'Follow' object has no attribute 'build_absolute_uri'

我不确定这意味着什么,因此我们将不胜感激。

这是回溯:

Traceback:
File "/Users/jphalis/Desktop/oby/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/jphalis/Desktop/oby/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)
File "/Users/jphalis/Desktop/oby/lib/python2.7/site-packages/django/views/generic/base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)
File "/Users/jphalis/Desktop/oby/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
  451.             response = self.handle_exception(exc)
File "/Users/jphalis/Desktop/oby/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
  448.             response = handler(request, *args, **kwargs)
File "/Users/jphalis/Desktop/oby/lib/python2.7/site-packages/rest_framework/generics.py" in get
  199.         return self.list(request, *args, **kwargs)
File "/Users/jphalis/Desktop/oby/lib/python2.7/site-packages/rest_framework/mixins.py" in list
  44.             return self.get_paginated_response(serializer.data)
File "/Users/jphalis/Desktop/oby/lib/python2.7/site-packages/rest_framework/serializers.py" in data
  618.         ret = super(ListSerializer, self).data
File "/Users/jphalis/Desktop/oby/lib/python2.7/site-packages/rest_framework/serializers.py" in data
  213.                 self._data = self.to_representation(self.instance)
File "/Users/jphalis/Desktop/oby/lib/python2.7/site-packages/rest_framework/serializers.py" in to_representation
  568.             self.child.to_representation(item) for item in iterable
File "/Users/jphalis/Desktop/oby/lib/python2.7/site-packages/rest_framework/serializers.py" in to_representation
  435.                 ret[field.field_name] = field.to_representation(attribute)
File "/Users/jphalis/Desktop/oby/lib/python2.7/site-packages/rest_framework/fields.py" in to_representation
  1330.         return method(value)
File "/Users/jphalis/Desktop/oby/src/accounts/serializers.py" in get_supporting
  124.         return serializer.data
File "/Users/jphalis/Desktop/oby/lib/python2.7/site-packages/rest_framework/serializers.py" in data
  618.         ret = super(ListSerializer, self).data
File "/Users/jphalis/Desktop/oby/lib/python2.7/site-packages/rest_framework/serializers.py" in data
  213.                 self._data = self.to_representation(self.instance)
File "/Users/jphalis/Desktop/oby/lib/python2.7/site-packages/rest_framework/serializers.py" in to_representation
  568.             self.child.to_representation(item) for item in iterable
File "/Users/jphalis/Desktop/oby/lib/python2.7/site-packages/rest_framework/serializers.py" in to_representation
  435.                 ret[field.field_name] = field.to_representation(attribute)
File "/Users/jphalis/Desktop/oby/lib/python2.7/site-packages/rest_framework/relations.py" in to_representation
  264.             return self.get_url(value, self.view_name, request, format)
File "/Users/jphalis/Desktop/oby/src/accounts/serializers.py" in get_url
  34.                        request=request, format=format)
File "/Users/jphalis/Desktop/oby/lib/python2.7/site-packages/rest_framework/reverse.py" in reverse
  26.     return _reverse(viewname, args, kwargs, request, format, **extra)
File "/Users/jphalis/Desktop/oby/lib/python2.7/site-packages/rest_framework/reverse.py" in _reverse
  39.         return request.build_absolute_uri(url)

Exception Type: AttributeError at /api2/follows/
Exception Value: 'Follow' object has no attribute 'build_absolute_uri'

我假设它指的是我的模型,所以这也是:

class Follow(models.Model):
    user = models.OneToOneField(MyUser)
    followers = models.ManyToManyField('self',
                                       related_name='following',
                                       symmetrical=False)

    class Meta:
        app_label = 'accounts'

    def __unicode__(self):
        return str(self.user.username)

MyUser.profile = property(lambda u: Follow.objects.get_or_create(user=u)[0])

提前感谢您的帮助!

- - 编辑:

serializers.py:

class FollowSerializer(serializers.HyperlinkedModelSerializer):
    username = serializers.CharField(source='user.username', read_only=True)
    supporters = serializers.SerializerMethodField(read_only=True)
    supporting = serializers.SerializerMethodField(read_only=True)

    def get_supporters(self, instance):
        queryset = Follow.objects.filter(following__pk=instance.pk)
        serializer = UserProfileSerializer(queryset,
                                           context="request": instance,
                                           many=True)
        return serializer.data

    def get_supporting(self, instance):
        queryset = Follow.objects.filter(followers__pk=instance.pk)
        serializer = UserProfileSerializer(queryset,
                                           context="request": instance,
                                           many=True)
        return serializer.data

    class Meta:
        model = Follow
        fields = [
            'username',
            'supporters',
            'supporting',
        ]

class UserProfileSerializer(serializers.HyperlinkedModelSerializer):
    account_url = UserProfileUrlField("user_profile_detail_api")
    username = serializers.CharField(source='user.username')

    class Meta:
        model = UserProfile
        fields = [
            'account_url',
            'username',
        ]

ListAPIView:

class FollowListAPIView(generics.ListAPIView):
    authentication_classes = [SessionAuthentication, BasicAuthentication, JSONWebTokenAuthentication]
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = FollowSerializer
    queryset = Follow.objects.all()

【问题讨论】:

你能分享你的序列化器和路由器吗?那里的“get_url”方法似乎发生了一些事情。 @bwarren2 添加了我的序列化程序。我没有为它设置路由器,只有一个直接从序列化程序提供的 ListAPIView。 看起来您正在通过 "request": instance 传递模型实例来代​​替请求变量。你为什么这样做?您也可以发布 UserProfileSerializer。 @bwarren2 我把它贴在FollowSerializer下面。我正在关注一个教程并试图模仿结果。有没有更好的方法来检索数据?也许为那个实例设置一个单独的序列化器? 你能发布你的 ListAPIView 吗? 【参考方案1】:

通过查看回溯,您似乎在 get_url() 函数中做错了,您在 serializers.py 中覆盖了该函数。

根据DRF docs,

此方法应返回对应于给定的 URL 对象。

DRF reverse() 函数的基本签名:

def reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra):

您必须为reverse() 中定义的参数传递正确的值。错误可能是由于向reverse() 函数发送了不正确的值。

【讨论】:

【参考方案2】:

现在,您传递的是模型实例,而不是序列化程序中的原始请求。

我怀疑您需要通过第一个序列化程序调用(在您的 ListAPIView 中)中的上下文传递请求,然后通过序列化程序类中的 self.context 访问它。 See here。这将允许您使用请求数据来构建 uri(并避免您现在遇到的“无属性”错误,因为您将传递该方法所期望的对象类型)。

这涉及覆盖 ListAPIView 中声明的 here 和 here 方法。

【讨论】:

以上是关于对象没有属性'build_absolute_uri' - Django Rest Framework的主要内容,如果未能解决你的问题,请参考以下文章

带有反向代理后面的HTTPS的build_absolute_uri

从 Django REST Framework 中的 APIView 中获取完整的请求 URL

如何在 Django(无需请求)中获取 URL(带有协议和域)?

为啥属性装饰器显示“对象没有属性”?

SparkContext' 对象没有属性 'prallelize

类型对象'用户'没有属性'对象django