Django 1.6: 无法在模板中显示模型中的图片。

2 投票
3 回答
836 浏览
提问于 2025-04-18 09:08

我想在页面上显示模型中的图片,但什么都没显示。我通过管理面板上传了图片,并且可以在上传文件夹里看到这张图片。但是当我在模板中尝试显示它时,还是没有任何东西显示出来。我在设置文件里没有相关的内容,比如媒体根路径和媒体网址,因为我不知道该填什么。

这是我尝试显示图片的模板

 <img src="{% url 'getDocProfilePicture' doctor.id %}">

这是 models.py 文件

class Doctor(models.Model):
    name = models.CharField(max_length=30)
    specialization = models.ForeignKey(Specialization)
    clinic = models.ForeignKey(Clinic)
    seekers = models.ManyToManyField(DoctorSeeker, through='Review')
    language = models.ManyToManyField(Language)
    education1 = models.CharField(max_length=100)
    education2 = models.CharField(max_length=100, null = True)
    gender_choices = ( ('M', 'Male'), ('F','Female'),)
    gender = models.CharField(max_length=5, choices = gender_choices, null=True)
    profile_pic = models.ImageField(upload_to='uploads/', null=True)
    statement = models.TextField(null=True)
    affiliation = models.CharField(max_length=100, null = True)

这是 views.py 文件

def getDocProfilePicture(request, id):
    d = Doctor.objects.get(id=doctor_id)
    return HttpResponse(d.profile_pic.read())

这是 urls.py 文件

url(r'^getDocProfileicture/ (?P<id>\d+)/$', views.getDocProfilePicture, name='getDocProfilePicture'),

3 个回答

0

我知道这个问题已经很久了,但我也遇到过同样的问题,这个方法对我有效:

settings.py

import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_DIR  = os.path.dirname(__file__)

MEDIA_ROOT = os.path.join(PROJECT_DIR, "media")

MEDIA_URL = '/media/'

urls.py

然后,我的urls.py文件里缺少了一行代码,这行代码是用来找到/media/文件夹并显示里面的内容的:

urlpatterns += staticfiles_urlpatterns()

urlpatterns = patterns('',
    url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}, name="media_url"),
) + urlpatterns

希望这能帮助到某些人。

0

在这里,你不需要使用 url 模板标签,也不需要单独写一个特别的视图。

只需要从 ImageField 中获取 url

<img src="{{ MEDIA_URL }}/{{ doctor.profile_pic.url }} ">
0

你不需要这么复杂的逻辑来显示图片。

{{ doctor.profile_pic.url }}

撰写回答