【问题标题】:How to link to user-uploaded profile pictures (ImageField) in Django templates?如何在 Django 模板中链接到用户上传的个人资料图片(ImageField)?
【发布时间】:2017-05-14 17:18:09
【问题描述】:

我有这个模型的实例:

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='profile', primary_key=True) #Each User is related to only one User Profile
    prof_pic = models.ImageField(blank=True, upload_to='profile_pictures')

所有头像都通过人口脚本上传到django_project_folder/media/profile_pictures

我可以通过上下文字典访问模板中的所有详细信息,但我不知道在图像标签中放置什么。

<img src=" what to put here?? " id="second" class="img-circle img-responsive">

我尝试像这样通过上下文字典链接 prof_pic,但它似乎损坏了:

<img src=" {{ req1.req1.traveler.profile.prof_pic }} " id="second" class="img-circle img-responsive">

我查看了this 文档,但不知道如何在模板中链接媒体文件。

我已经完成了 MEDIA_ROOT 配置,并且我已经知道如何链接静态文件。

【问题讨论】:

    标签: python django templates django-models


    【解决方案1】:

    当您访问 UserProfile 模型实例的 prof_pic 属性时,您会得到一个具有 url 属性的 FieldFile 对象。请尝试以下操作:

    <img src="{{ req1.req1.traveler.profile.prof_pic.url }}" id="second" class="img-circle img-responsive">
    

    延伸阅读:FileField and FieldFile.

    【讨论】:

      猜你喜欢
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 2011-09-14
      • 2014-01-30
      • 2017-07-10
      • 2014-10-05
      • 2013-04-29
      • 2011-11-07
      相关资源
      最近更新 更多