gpt4 book ai didi

python - 在 Django 模板中显示图像

转载 作者:太空狗 更新时间:2023-10-29 18:26:40 24 4
gpt4 key购买 nike

谁能帮我解决这个问题:我有一个 Django 项目,

在 settings.py 中

 MEDIA_ROOT = 'C:/Users/hl/workspace/beer/media'
MEDIA_URL = '/media/'
STATICFILES_DIRS = (
'C:/Users/hl/workspace/beer/media'
)

在 models.py 中

image1= models.ImageField(upload_to=settings.MEDIA_ROOT)

在 url.py 中

 (r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),

在 View 中

def allBeer(request): 
beers=Beer.objects.all().order_by("name")
context={'beers': beers}
return render_to_response('AllBeers.html',context,context_instance=RequestContext(request))

在 html 中

 {%for beer in beers %}
<p>
<a href="/beers/{{beer.slug}}/">
<img scr="{{beer.image1.url}}">{{beer}}
</a>
</p>
{% endfor%}

加载图像没有问题,但图像不会显示在 html 文件中。我已经在互联网上搜索和阅读了很多,但我仍然无法弄清楚。

谁能告诉我为什么?

最佳答案

image1= models.ImageField(upload_to=images)


from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from project_name import settings

admin.autodiscover()
urlpatterns = patterns('',
...........
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += staticfiles_urlpatterns()


<img src="{{MEDIA_URL}}{{beer.image1}}">

settings.py

import os

PROJECT_ROOT = os.path.join(os.path.dirname(__file__), '..')
SITE_ROOT = PROJECT_ROOT


MEDIA_ROOT = os.path.join(SITE_ROOT, 'media')
MEDIA_URL = '/media/'


STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
STATIC_URL = '/static/'


STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
os.path.join(SITE_ROOT, 'staticfiles'),
)

TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(SITE_ROOT, 'templates'),
)

关于python - 在 Django 模板中显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15175032/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com