1

I have a piece of code in views.py that gets the file names from a directory:

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 )
context = {'imageArray': imageArray}
print context
return render(request, 'imgpage/add_category.html',context)



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

I want to use this array of image files in javascript. I want to use the array of file names so that I can use js to change image source. The print context statement yields the following output in the python console:

{'imageArray': ['image0.jpg', 'image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.
jpg', 'image5.jpg', 'image6.jpg', 'image7.jpg', 'image8.jpg', 'image9.jpg']}

But I am not able to access the imageArray at all in the template. Here are the scripts I tried to test if the array has been passed, in the template html file:

In add_category.html file:

{% for img in imageArray %}
        <li>{{ img|safe }}</li>
        <li>{{ img }}</li>
        <p>img</p>
{% endfor %}

Also, note that the "img" inside <p> tags are also not rendered on the screen.

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

In the above script, the first console log prints empty line in the console, while the 2nd prints "imgx=undefined"

Please suggest me ways I can use the python list as JS array. I use Django 1.8.1, but the service I would host on uses 1.7.x. So something that would work on both would be great.

2 Answers 2

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})
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the quick response! Anyway, I modified my views.py like this: else: imageArray = imgArray(request) context = {'imageArray': imageArray} return render(request, 'imgpage/add_category.html',context) where imageArray has the list returned by the imgArray function. Now the console prints this: ['image0.jpg', 'image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg', 'image6.jpg', 'image7.jpg', 'image8.jpg', 'image9.jpg'] imgx= How do I get the imgx to be a filename?
You've enclose the Django variable in quotes in your JS code. So JS will see it as a string. Really you should use JSON to pass values between Django and JS.
Thanks a bunch! Worked fine on using JSON.
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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.