I have a small project of the backoffice for a pos program. actually the images are stored in binary field so, I must work with them. As example I have the following model for one categories table: models.py
class Categories(models.Model):
id = models.CharField(primary_key=True, max_length=20, default=createid())
name = models.CharField(unique=True, max_length=50)
parentid = models.ForeignKey('self', db_column='parentid', blank=True, null=True)
image = models.ImageField(upload_to="images", null=True)
def __unicode__(self): # __unicode__ on Python 2
return '('+self.id+')'+self.name
def save(self, *args, **kwargs):
try:
path1 = safe_join(os.path.abspath(settings.MEDIA_ROOT)+'\images', self.image)
image_file = open(path1,'rb')
file_content = image_file.read()
self.image=file_content
except:
filename = 'no_image.png'
path = safe_join(os.path.abspath(settings.MEDIA_ROOT), filename)
#if not os.path.exists(path):
# raise ObjectDoesNotExist
no_image = open(path, 'rb')
file_content = no_image.read()
super(Categories, self).save(*args, **kwargs)
def image_thumb(self):
if self.image:
file_like=cStringIO.StringIO(self.image)
return mark_safe(u'<img width="70" height="70" src="data:image/png;base64,%s" />') % file_like
else:
return '(No image)'
image_thumb.short_description = 'Thumb'
image_thumb.allow_tags = True
class Meta:
managed = False
db_table = 'categories'
To avoid the database unnecessery structure changes, in models.py I changed the image column type to models.ImageField. In Database it is a binary field. Doing this and by overiding save method, i try to resolve the problem.
1)But when Itry to save the uploaded file I receive the following message:
DjangoUnicodeDecodeError at /admin/app/categories/34/ 'utf8' codec can't decode byte 0x89 in position 0: invalid start byte. You passed in '\x89PNG\r\n\x1a\n\x....<
2) I cannot retrieve the right format to display image in file_like varible
I use python 2.7 and django 1.7
Any help is highly happreciated