[Answer]-Django using {{ MEDIA_URL }} in template with HttpResponse

1👍

✅

Turned out I didn’t need any of those. Since I’m using nginx to handle my site, I just added media path to nginx locations

location /media/ {
               autoindex on;
               alias mysitepath/media/;
          }

and changed my html code like this

<img src="/media/{$ image.imgs $}" />

So now everythong works just fine

0👍

You’re not passing the MEDIA_URL variable in your response’s context. You should be doing something like this:

from django.conf import settings
data = {'pictures': dictionaries, 'mediaUrl': settings.MEDIA_URL}

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

In your angular code:

$http.get("imagelist/").success(function(data) {
      $scope.pictures = data.pictures;
      $scope.mediaUrl = data.mediaUrl;
});

And in your template

<img src="{$ mediaUrl $}{$ image.imgs $}" />

That way, the media url is passed from your settings down to your angular app and loaded in the angular template (all of this could use better naming though, but you get the idea).

Leave a comment