[Answered ]-Using list from views in Django 1.8.1 as an array in javascript template

1👍

You have a very peculiar structure here. imageArray() is a view, which returns a full HttpResponse; but you call it from within another view, add_category. What’s more, you do nothing at all with the result; it is thrown away and never passed anywhere. So, naturally, it’s always going to be blank in the template.

I’m not sure exactly what you’re doing, so it’s hard to know what you really want here. But I suspect that imageArray() should be a normal utility method, which simply returns a list of images:

def imgArray():
    filepath = os.path.join(STATIC_PATH, "\\images")
    images =[f for f in os.listdir(filepath) if f.endswith('.jpg')]
    return images

Then you need to actually do something with that value in your add_category function:

def add_category(request):
    ...
    else:
        imageArray = imgArray()
    return render(request, 'imgpage/add_category.html', {imageArray: imageArray})

1👍

So here is what I did:
views.py

#importing json
import json
from django.core.serializers.json import DjangoJSONEncoder

def imgArray(request):
    filepath = STATIC_PATH+"\\images"
    imageArray=[]
    ext='.jpg'
    for i in os.listdir(filepath):
        if(os.path.splitext(i)[1] == ext):      
             imageArray.append( i )
    json_list = json.dumps(list(imageArray), cls=DjangoJSONEncoder)
    return json_list

def add_category(request):
    # A HTTP POST?
    if request.method == 'POST':
        #Do something
    else:
        # If the request was not a POST, display the form to enter details.
        imageArray = imgArray(request)
        context = {'imageArray': imageArray}
        return render(request, 'imgpage/add_category.html',context)

    return render(request, 'imgpage/add_category.html')

And in add_category.html:

<script type="text/javascript">
            var images = {{imageArray|safe}};               
            document.getElementsByTagName("img")[0].src =  DJANGO_STATIC_URL+"images/"+images[1];
        </script>

Hope this helps someone 🙂
Cheers!

Leave a comment