victor reyes1 victor reyes1 - 20 days ago 7
Ajax Question

Django, Ajax and Fotorama DB update

I'm trying to get images added to Fotorama Image slider from Django DB so far with no luck i would tremendously appreciate any assistance.
I'm able to see the AJAX function returns values on the inspector console how ever cant get slider to display them.

this is my urls.py

url(r'image/busqueda/$', views.ImageBusqueda.as_view(), name='image-busqueda'),


this is my views.py

class ImageBusqueda(generic.TemplateView):

def get(self, request, *args, **kwargs):
images = Images.objects.all()
data = serializers.serialize('json' ,images, fields=
('imagen','nombre','duracion'))
return HttpResponse(data)


and this is my JS

<script>
$(function () {
$('.fotorama')


.on('fotorama:show', function() {

$.ajax({
url:'/image/busqueda/',
type:'get',
datatype:'json',
success : function(data){
var img = ""
for(var i = 0; i<data.lenght; i ++ ){
img += '<img src="' + data[i].fields.imagen + '"data-id="' + data[i].id + '">'

}
$('#img').html(img);
}

});

})
</script>


this is the HTML

<div class="fotorama"
data-nav="false"
data-shuffle="true"
data-autoplay="true"
data-arrows="false"
data-loop="true"
data-transition="dissolve"
data-fit="cover"
data-width="100%"
data-height="100%"
>
{# NORMAL DJANGO WAY #}
{# {% for img in imagenes %}#}
{# <img src="{{ img.imagen.url }}" data-id="{{ img.id }}" >#}
{# {% endfor %} #}


{# JS WAY #}
<div id="img">

</div>


</div>

Answer Source

To build upon my comment, here's a minimal for loop to serialize your model:

import json

class ImageBusqueda(generic.TemplateView):

    def get(self, request, *args, **kwargs):
        images =  Images.objects.all()

        data_list = []
        for image in queryset:
            data_list.append({
                'imagen': image.imagen.url,
                'nombre': image.nombre,
                'duracion': image.duracion
            })

       data = json.dumps(data_list)
       return HttpResponse(data, content_type='application/json')

NOTE: This approach of manually serializing objects is pretty good if you have to use it in one view. If you want to use it in multiple views, I'd recommond that you move this into a separate function solely dedicated to serializing. That way you can access it in other views as well instead of just copying the code again and again.