【问题标题】:Django 1.6: Can't display a picture from a model in template.Django 1.6:无法在模板中显示来自模型的图片。
【发布时间】:2014-06-09 14:30:02
【问题描述】:

我正在尝试显示模型中的图片,但它没有显示任何内容。我使用管理面板上传了图片,我可以在上传文件夹中看到图片。但是当我尝试在模板中显示它时,它什么也没显示。我没有任何与之相关的设置文件,例如媒体根目录、媒体 URL,因为我不知道该为他们放什么

这是我要展示的模板

 <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())

网址.py

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

【问题讨论】:

    标签: python django image templates


    【解决方案1】:

    显示图像不需要这么复杂的逻辑。

    {{ doctor.profile_pic.url }}
    

    【讨论】:

    • 如果我输入 {{ doctor.profile_pic.url }} 它会显示这个 uploads/_20140601_233911.JPG
    • 你需要把它放在图片标签中。像这样 。我只是展示如何在模板中获取图像 url。
    • 这意味着您没有正确调整服务媒体文件。现在您有了正确的图片网址。但它不起作用,因为您的应用程序不返回媒体文件。希望这对你有用docs.djangoproject.com/en/dev/howto/static-files/…
    • @HarisAghadi 查看我的答案(您可能需要在前面加上MEDIA_URL)。
    【解决方案2】:

    您不需要在这里使用url 模板标签并有一个特殊的单独视图。

    只需从ImageField 获取url

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

    【讨论】:

      【解决方案3】:

      我知道这个问题很老,但我遇到了同样的问题,这在我的情况下解决了:

      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
      

      希望它可以帮助某人。

      【讨论】:

        猜你喜欢
        • 2014-07-28
        • 2021-05-18
        • 2021-02-14
        • 1970-01-01
        • 2011-11-17
        • 2015-02-13
        • 2012-05-15
        • 1970-01-01
        • 2014-08-12
        相关资源
        最近更新 更多