python - 使用 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)
解决方案
您的方法get_profile_pic
返回一个ImageFieldFile
对象而不是str
.
您应该使用以下url
属性:
def get_profile_pic(self, photo):
photo_url = photo.author.profile_pic.url
return photo_url
请参阅在模型中使用文件
推荐阅读
- r - 找到模式被破坏的地方并告诉我在哪里看
- mongodb - Mongoimport命令在Windows中不起作用
- ignite - 默认情况下,Ignite 服务器在禁用 jmx 的情况下运行
- python - 如何再次检查用户输入值 Django 模型和表单
- kotlin - kotlin - 如何使用空检查最小化 if 语句
- python - 从 Azure AD 获取员工 ID
- react-native - WebSQL 抛出错误 [错误:错误代码 1:没有这样的表:文档存储]
- angular - ngcc 未正确处理 MatPaginator
- flutter - 我未来的方法不能正常工作,同时使用颤振构建器小部件,我哪里出错了?
- php - 如何在 Prestashop 中按 CategoryId 获取产品?