首页 > 解决方案 > 使用 django 序列化程序时出现 UnicodeDecodeError

问题描述

我有一个自定义 django 用户模型和一个外键为“CustomUser”模型的“照片”模型:

class CustomUser(AbstractUser):

    REQUIRED_FIELDS = []
    USERNAME_FIELD = 'email'

    objects = CustomUserManager()
    email = models.EmailField(_('email address'), unique=True)
    username = models.CharField(max_length=10)
    bio = models.CharField(max_length=240, blank=True)
    city = models.CharField(max_length=30, blank=True)
    profile_pic = models.ImageField(null=True, blank=True)
    date_of_birth = models.DateField(blank=True, null=True)

    def __str__(self):
        return self.email

class Photo(models.Model):
    image = models.ImageField(blank=False, null=False, upload_to="images")
    author = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE)
    title = models.CharField(max_length=200)

    def __str__(self):
        return self.title

我正在尝试从 Photo Serializer 获取“profile_pic”字段(在 CustomUser 中定义),但出现 utf-8 错误。 错误图像

照片序列化器:

class PhotoSerializer(ModelSerializer):

    email = serializers.SerializerMethodField('get_user_email')
    username = serializers.SerializerMethodField('get_username')
    profile_pic = serializers.SerializerMethodField('get_profile_pic')
    
    class Meta:
        model = Photo
        fields = ['id', 'author','image', 'title','email', 'username', 'profile_pic']

    def get_user_email(self, photo):
        email = photo.author.email
        return email

    def get_username(self, photo):
        username = photo.author.username
        return username
        
    def get_profile_pic(self, photo):
        photo_url = photo.author.profile_pic  
        return photo_url

如果我用下面的代码替换 get_profile_pic,它会给出正确的图像 url。但是还有其他方法吗?另外我想知道错误的原因。

def get_profile_pic(self, photo):
        request = self.context.get('request')
        photo_url = photo.author.profile_pic  
        photo_url = 'media/' + str(photo_url)
        return request.build_absolute_uri(photo_url)

标签: pythondjangodjango-modelsdjango-rest-frameworkdjango-serializer

解决方案


您的方法get_profile_pic返回一个ImageFieldFile对象而不是str.

您应该使用以下url属性:

def get_profile_pic(self, photo):
    photo_url = photo.author.profile_pic.url
    return photo_url

请参阅在模型中使用文件


推荐阅读