\project_structure
-app
\project
-settings.py
-...
\picture
-panda.jpg
我已将图片上传到picture
。
class Goods(models.Model):
pic = models.ImageField(upload_to='picture')
database
中的数据是 picture / panda.jpg
现在,我怎样才能在html中显示它?
我在html中写道:
<p>{{each.pic}}</p>
<img src='{{ each.pic.url }}' />
浏览器中的源代码是:
picture/panda.jpg
<img src='picture/panda.jpg' />
图片已与 http://localhost:8000/my_sell/picture/panda.jpg 相关联。并且无法显示。
我如何解决此问题,我已尝试在media_root
中添加settings.py
并且无用。
答案 0 :(得分:2)
没有检查这个,但几乎所有代码都来自我的工作项目:)。
settings.py
:
MEDIA_URL = '/media/'
MEDIA_ROOT = (
os.path.join(BASE_DIR, 'media')
)
models
:
from django.core.files.storage import FileSystemStorage
from django.conf import settings
image_storage = FileSystemStorage(
# Physical file location ROOT
location=u'{0}/my_sell/'.format(settings.MEDIA_ROOT),
# Url for file
base_url=u'{0}my_sell/'.format(settings.MEDIA_URL),
)
def image_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/my_sell/picture/<filename>
return u'picture/{0}'.format(, filename)
class Goods(models.Model):
pic = models.ImageField(upload_to=image_directory_path, storage=image_storage)
views
:
from django.shortcuts import render
def view_picture(request):
c = dict()
c['goods'] = Goods.objects.all()
return render(request, 'template.html', c)
templates
:
{% for product in goods %}
{% if product.pic %}
<img src="{{ product.pic.url }}">
{% endif %}
{% endfor %}
已修改:不要忘记将MEDIA_URL添加到根urls.py
if settings.DEBUG
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)