I'm trying to make image field optional in serializer. But it still not making the image field optional. My code are as bellow:
Photo Uploading file managing class:
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}'
My Model class:
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)
My Serializer Class:
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
The error Text:
ValueError at /forum/write-blog
The 'content_image' attribute has no file associated with it.
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.
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)