0

I'm trying to pass the URL's of a list of photos to the template. I'm concatenating my MEDIA_URL to every photo name.

When print(a) is run, I can see in the console that the concatenation was successfully added. The result is something like media/photo.jpg. However by the time the loop finishes, the result reverts back to the original photo.jpg as if no concatenation happened. print(photos) shows a list of photos with no changes.

Why?

def get_property_data(request):
    property_id = request.GET.get('id')
    photos = ListingPhoto.objects.values_list('photo', flat=True).filter(listing__id=property_id)
    for a in photos:
        a = settings.MEDIA_URL + a
        print(a)
    print(photos)

    return JsonResponse({'property': list(photos)})
1
  • 2
    In for a in photos, a is copy of the elements inside photos. Therefore modifying a doesn't modify the values in the iterable photos. Maybe you want: for i in range(len(photos)): photos[i] += settings.MEDIA_URL. Commented Dec 23, 2017 at 3:29

1 Answer 1

1

You are outputting photos which is unchanged. Also you are looping through on a and changing the value, over and over again.

Try something like this instead

b = []
for a in photos:
        b.append(settings.MEDIA_URL + a)
        print(a)
print(b) # b is an array of url strings
Sign up to request clarification or add additional context in comments.

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.