尝试访问Django Rest Framework

时间:2016-01-17 08:20:06

标签: python django django-rest-framework

使用PostSerializer时出现以下错误:

  

尝试获取字段值时出现AttributeError   序列化程序full_name上的UserSerializer。序列化器字段可能   被错误命名并且不匹配long上的任何属性或键   实例。原始异常文本是:'long'对象没有属性   'FULL_NAME'。

序列化程序如下:

class PostSerializer(serializers.ModelSerializer):
    author = UserSerializer(required=False, allow_null=True)
    class Meta:
        model = Post
        fields = ('id', 'author', 'message', 'rating', 'create_date', 'close_date',)

class UserSerializer(serializers.ModelSerializer):
   class Meta:
       model = User
       fields = ('id', 'username', 'full_name',)

查看:

class PostMixin(object):
    model = Post
    serializer_class = PostSerializer
    permission_classes = [
        PostAuthorCanEditPermission
    ]
    queryset = model.objects.all()

    def pre_save(self, obj):
        """Force author to the current user on save"""
        obj.author = self.request.user
        return super(PostMixin, self).pre_save(obj)


class PostList(PostMixin, generics.ListCreateAPIView):
    pass

用户模型:

class User(AbstractBaseUser):
    email = models.EmailField(unique=True)
    username = models.CharField(max_length=40, unique=True, null=True)
    full_name = models.CharField(max_length=50, blank=False)
    phone = models.CharField(max_length=20, unique=True, null=True)
    about = models.CharField(max_length=255, blank=True)
    type = models.CharField(max_length=1, default='U')
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(auto_now_add=True)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['full_name']

    def __unicode__(self):
        return self.email

    def get_full_name(self):
        return self.full_name

    def get_short_name(self):
        return self.full_name

2 个答案:

答案 0 :(得分:1)

问题

  

尝试在序列化程序UserSerializer上获取字段full_name的值时出现AttributeError。

Django中的模型User没有名为full_name的字段。 虽然方法get_full_name()可以做你想要的。

解决方案

因此,请尝试通过Installing SFML

使用它
class UserSerializer(serializers.ModelSerializer):
   class Meta:
       model = User
       fields = ('id', 'username') # no full_name here

   full_name = serializers.SerializerMethodField('get_full_name')

这将为您的序列化对象添加一个名为full_name的字段,其值从User.get_full_name()

拉出

检查您使用的是自定义模型,而不是Django的用户模型

您已经自定义了自己的User模型,但由于该模型有full_name,因此您不应该首先得到该错误,因此请仔细检查您是不是首先引用Django的默认User模型。

class UserSerializer(serializers.ModelSerializer):
   class Meta:
       model = User # <--- Make sure this is your app.models.User,
                    # and not Django's User model
       fields = ('id', 'username', 'full_name',) # This is OK on your User model

答案 1 :(得分:0)

或只是

 <uses-permission android:name="android.permission.EXPAND_STATUS_BAR" />