Django Rest Framework可选图像字段不起作用 [英] Django Rest Framework Optional Image field is not working
问题描述
我正在尝试使图像字段在序列化器中为可选。但是它仍然不能使image字段成为可选字段。我的代码如下:
I'm trying to make image field optional in serializer. But it still not making the image field optional. My code are as bellow:
照片上传文件管理类:
class FileManager:
@staticmethod
def photo_path(instance, filename):
basefilename, file_extension = os.path.splitext(filename)
date = datetime.datetime.today()
uid = uuid.uuid4()
if isinstance(instance, User):
return f'profile_pic/{instance.email}/{uid}-{date}{file_extension}'
elif isinstance(instance, BlogPost):
print(file_extension)
return f'blog_pic/{instance.author.email}/{uid}-{date}{file_extension}'
我的模型类:
class BlogPost(models.Model):
'''
Manage Blog Posts of the user
'''
author = models.ForeignKey(get_user_model(),
on_delete=models.DO_NOTHING,
related_name='blog_author')
content = models.TextField(max_length=600, blank=True, null=True)
content_image = models.FileField(upload_to= FileManager.photo_path, null=True, blank=True)
is_approved = models.BooleanField(default=False)
updated_on = models.DateTimeField(auto_now_add=True)
timestamp = models.DateTimeField(auto_now_add=True)
def save(self, *args, **kwargs):
super(BlogPost, self).save(*args, **kwargs)
img = Image.open(self.content_image.path)
if img.height > 600 or img.width > 450:
output_size = (600, 450)
img.thumbnail(output_size)
img.save(self.content_image.path)
我的序列化器类:
class BlogPostUserSerializer(serializers.HyperlinkedModelSerializer):
'''
Will be serializing blog data
'''
author = UserListSerializer(read_only=True)
content = serializers.CharField(required=False)
content_image = serializers.ImageField(required=False, max_length=None, allow_empty_file=True, use_url=True)
class Meta:
model = BlogPost
fields = (
'url',
'id',
'content',
'content_image',
'author')
def validate(self, data):
if not data.get('content') and not data.get('content_image'):
raise serializers.ValidationError({'message':'No-content or Content image were provided'})
return data
错误文本:
ValueError at / forum / write-blog
ValueError at /forum/write-blog
content_image属性没有与之关联的文件。
The 'content_image' attribute has no file associated with it.
我已经遍历了Django Rest Framework的文档,但没有帮助。甚至其他人的答案也无法正常工作,请帮助我。 p>
I've gone through the Django Rest Framework's Doc but no help. Even the answers of others isn't working please help I'm stuck.
推荐答案
实际上,我已经解决了这个问题。现在我知道它从来都不是来自我的序列化程序类。
Actually I've solved the problem. It was never coming from my Serializer Class now that I see.
实际上,它来自我模型类的Save方法。在保存时尝试修改图像的位置,但由于模型字段为空,因此抛出错误。我解决的代码。
In fact it was coming from my model class's Save method. where it was trying to modify the image while saving but since the model field is empty it throws an error instead. My solved code.
class BlogPost(models.Model):
'''
Manage Blog Posts of the user
'''
author = models.ForeignKey(get_user_model(),
on_delete=models.DO_NOTHING,
related_name='blog_author')
content = models.TextField(max_length=600, blank=True, null=True)
content_image = models.FileField(upload_to= FileManager.photo_path, null=True, blank=True)
is_approved = models.BooleanField(default=False)
updated_on = models.DateTimeField(auto_now_add=True)
timestamp = models.DateTimeField(auto_now_add=True)
def save(self, *args, **kwargs):
super(BlogPost, self).save(*args, **kwargs)
if self.content_image:
img = Image.open(self.content_image.path)
if img.height > 600 or img.width > 450:
output_size = (600, 450)
img.thumbnail(output_size)
img.save(self.content_image.path)
class Meta:
unique_together = ( 'author',
'content',
'content_image')
在这里我添加了一个条件,说明是否有图像,然后对其进行修改。
Here I've added a condition that says if there is an image then modify it.
if self.content_image:
img = Image.open(self.content_image.path)
这篇关于Django Rest Framework可选图像字段不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!