The idea is I want my form to upload an image with ImageField and then save a base64 of that image with post_save.
Model :
class Feed(models.Model):
id = models.BigAutoField(primary_key=True)
title = models.CharField(max_length = 200)
content = models.TextField()
thumbnail = models.ImageField(upload_to='feeds/', blank=True)
img_b64 = models.BinaryField(blank=True, null=True)
author = models.ForeignKey(Account, on_delete=models.CASCADE)
date = models.DateTimeField(auto_now_add=True)
view = models.IntegerField(default=0)
kategori = models.CharField(max_length=100, default="None")
post_save :
@receiver(post_save, sender=Feed)
def save_base64(sender, instance, **kwargs):
if instance.thumbnail:
img_file = open(instance.thumbnail.url, "rb")
instance.image_b64 = base64.b64encode(img_file.read())
instance.save()
but I get a FileNotFound error:
Traceback (most recent call last):
File "D:\Project\Lapor Hoax\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "D:\Project\Lapor Hoax\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Project\Lapor Hoax\env\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "D:\Project\Lapor Hoax\laporhoax\account\views.py", line 123, in isi_berita_view
form.save()
File "D:\Project\Lapor Hoax\env\lib\site-packages\django\forms\models.py", line 468, in save
self.instance.save()
File "D:\Project\Lapor Hoax\env\lib\site-packages\django\db\models\base.py", line 726, in save
self.save_base(using=using, force_insert=force_insert,
File "D:\Project\Lapor Hoax\env\lib\site-packages\django\db\models\base.py", line 774, in save_base
post_save.send(
File "D:\Project\Lapor Hoax\env\lib\site-packages\django\dispatch\dispatcher.py", line 180, in send
return [
File "D:\Project\Lapor Hoax\env\lib\site-packages\django\dispatch\dispatcher.py", line 181, in <listcomp>
(receiver, receiver(signal=self, sender=sender, **named))
File "D:\Project\Lapor Hoax\laporhoax\feed\models.py", line 43, in save_base64
img_file = open(instance.thumbnail.url, "rb")
Exception Type: FileNotFoundError at /berita/add/
Exception Value: [Errno 2] No such file or directory: '/media/feeds/sisi_q1f0hdr.jpeg'
where did it go wrong? or if somebody can come up with a better idea to save a base64 with ImageField will be much appreciated
CodePudding user response:
Why don't you just override save method in model, if you want to have just another base 64 image field.
class ExampleModel(models.Model):
image = models.ImageField()
base_64_image = models.BinaryField()
def save(self):
self.base_64_image = get_base_64_image(self.image.file)
return super().save()```