如何解决UnicodeDecodeError:'utf-8'编解码器无法解码位置0的字节0xff:Django中的无效起始字节
我想通过get请求获取api列表。但是在编写代码后,我发送了get请求,并出现以下错误。
追踪
Traceback (most recent call last):
File "C:\Users\kurak\AppData\Local\Programs\Python\python38-32\lib\site-packages\django\core\handlers\exception.py",line 34,in inner
response = get_response(request)
File "C:\Users\kurak\AppData\Local\Programs\Python\python38-32\lib\site-packages\django\core\handlers\base.py",line 145,in _get_response
response = self.process_exception_by_middleware(e,request)
File "C:\Users\kurak\AppData\Local\Programs\Python\python38-32\lib\site-packages\django\core\handlers\base.py",line 143,in _get_response
response = response.render()
File "C:\Users\kurak\AppData\Local\Programs\Python\python38-32\lib\site-packages\django\template\response.py",line 105,in render
self.content = self.rendered_content
File "C:\Users\kurak\AppData\Local\Programs\Python\python38-32\lib\site-packages\rest_framework\response.py",line 70,in rendered_content
ret = renderer.render(self.data,accepted_media_type,context)
File "C:\Users\kurak\AppData\Local\Programs\Python\python38-32\lib\site-packages\rest_framework\renderers.py",line 100,in render
ret = json.dumps(
File "C:\Users\kurak\AppData\Local\Programs\Python\python38-32\lib\site-packages\rest_framework\utils\json.py",line 25,in dumps
return json.dumps(*args,**kwargs)
File "C:\Users\kurak\AppData\Local\Programs\Python\python38-32\lib\json\__init__.py",line 234,in dumps
return cls(
File "C:\Users\kurak\AppData\Local\Programs\Python\python38-32\lib\json\encoder.py",line 199,in encode
chunks = self.iterencode(o,_one_shot=True)
File "C:\Users\kurak\AppData\Local\Programs\Python\python38-32\lib\json\encoder.py",line 257,in iterencode
return _iterencode(o,0)
File "C:\Users\kurak\AppData\Local\Programs\Python\python38-32\lib\site-packages\rest_framework\utils\encoders.py",line 50,in default
return obj.decode()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
在前面的代码中,我们正常收到它,没有任何解码错误,并且修改后会发生此问题。有什么问题?这是我的代码。
views.py
class CreateReadPostView (ModelViewSet) :
serializer_class = PostSerializer
permission_classes = [IsAuthenticated]
queryset = Post.objects.all()
def perform_create (self,serializer) :
serializer.save(author=self.request.user)
def list (self,request) :
posts = Post.objects.all()
data = []
for post in posts :
comments = Comment.objects.filter(post=post)
json = {
'pk': post.pk,'author': {
'email': post.author.email,'username': post.author.username,'profile': post.author.profile
},'like': post.liker.count,'liker': post.liker,'text': post.text,'images': Image.objects.filter(post=post),'comments_count': comments.count(),'view': post.view,'viewer_liked': None,'tag': post.tag
}
data.append(json)
return Response(data,status=200)
serializers.py
class ImageSerializer (serializers.ModelSerializer) :
image = serializers.ImageField(allow_null=True,use_url=True)
class Meta :
model = Image
fields = ['image']
class PostSerializer (serializers.ModelSerializer) :
author = serializers.CharField(source='author.username',read_only=True)
title = serializers.CharField(allow_null=True)
text = serializers.CharField(allow_null=True)
image = ImageSerializer(many=True,allow_null=True,read_only=True)
class Meta:
model = Post
fields = ['pk','author','title','text','like','liker','image','view']
def validate (self,attrs) :
title = attrs.get('title','')
text = attrs.get('text','')
image = attrs.get('image','')
error = {}
if title is None and text is None and image is None :
error['message'] = '제목,본문,그리고 이미지를 넣어주세요.'
raise serializers.ValidationError(error)
if title is None and text is None :
error['message'] = '제목과 본문을 넣어주세요.'
raise serializers.ValidationError(error)
if title is None and image is None :
error['message'] = '제목과 이미지를 넣어주세요.'
raise serializers.ValidationError(error)
if text is None and image is None :
error['message'] = '본문과 이미지를 넣어주세요.'
raise serializers.ValidationError(error)
if title is None :
error['message'] = '제목을 넣어주세요.'
raise serializers.ValidationError(error)
if text is None :
error['message'] = '본문을 넣어주세요.'
raise serializers.ValidationError(error)
if image is None :
error['message'] = '이미지를 넣어주세요.'
raise serializers.ValidationError(error)
return attrs
def create (self,validated_data) :
images_data = self.context['request'].FILES
post = Post.objects.create(**validated_data)
for image_data in images_data.getlist('image') :
Image.objects.create(post=post,image=image_data)
return post
models.py
from django.db import models
from django.conf import settings
class Post (models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name='author',null=True)
title = models.CharField(max_length=40)
text = models.TextField(max_length=300)
tag = models.CharField(max_length=511,null=True)
view = models.IntegerField(default=0)
viewer = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='viewer',blank=True)
like = models.IntegerField(default=0)
liker = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='liker',blank=True)
def __str__ (self) :
return self.title
class Image (models.Model) :
post = models.ForeignKey(Post,on_delete=models.CASCADE)
image = models.ImageField(null=True,blank=True)
class Comment (models.Model) :
author = models.ForeignKey(settings.AUTH_USER_MODEL,null=True)
post = models.ForeignKey(Post,on_delete=models.CASCADE)
text = models.TextField(max_length=200)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。