簡體   English   中英

Django在帶有HttpResponse的模板中使用{{MEDIA_URL}}

[英]Django using {{ MEDIA_URL }} in template with HttpResponse

我正在嘗試在模板標簽中使用{{MEDIA_URL}}。 這是我的html代碼:

<li data-ng-repeat="image in pictures[currentCat]">
    <a>
        <img src="{{ MEDIA_URL }}{$ image.imgs $}" />
    </a>
</li>

我正在將json發送到js並在AngularJS中使用它

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

我已經將這部分添加到我的setting.py

TEMPLATE_CONTEXT_PROCESSORS = (
  "django.contrib.auth.context_processors.auth",
  "django.core.context_processors.media",
)

現在這個答案建議這樣做

 from django.template.context import RequestContext context = {'latest': p} render_to_response('Question/latest.html', context_instance=RequestContext(request, context)) 

但是我正在使用HttpResponse ,它不適用於我的代碼。

def getimagelist(request):
    dictionaries=[]
    for cat in Category.objects.all():
        dictionary=[obj.as_json() for obj in Gallery.objects.filter(cat_id=cat.id)]
        dictionaries.append(dictionary)
    return HttpResponse(json.dumps(dictionaries), content_type='application/json')

我的問題是使用HttpResponse時如何在代碼中使用{{ MEDIA_URL }}

目前,它在我的html中顯示為空白。 謝謝

原來我不需要這些。 由於我使用nginx處理我的網站,因此我只將媒體路徑添加到nginx位置

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

並像這樣更改了我的html代碼

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

所以現在一切都很好

您沒有在響應的上下文中傳遞MEDIA_URL變量。 您應該這樣做:

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

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

在您的角度代碼中:

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

並在您的模板中

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

這樣,媒體網址就會從您的設置傳遞到您的Angular應用程序中,並加載到Angular模板中(盡管所有這些都可以使用更好的命名,但是您可以理解)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM