Get random item with image encoded with base 64 (AJAX)
For example we have model like this
class Photo(models.Model):
title = models.CharField(max_lenght=255)
image = models.FileField(upload_to='photos')
And we want to get info about random Photo, including image in base64 encoding:
def ajax_get_random_photo(request):
try:
photo = Photo.objects.order_by('?')[0]
response = simplejson.dumps({
'status': True,
'title': photo.title,
'image': open(photo.image.file.name, "rb").read().encode("base64")
}, ensure_ascii=False)
except:
response = simplejson.dumps({'status': False})
return HttpResponse(response, mimetype='application/json; charset=utf-8')
Written by Dmitry Belaventsev
Related protips
1 Response
Just keep in mind that order_by('?') could be really slow on some database backends if you have a big set of rows there.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#