Last Updated: February 25, 2016
·
1.758K
· dizpers

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')

1 Response
Add your 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 ·