首页 > 解决方案 > 如何从配置文件模型中获取图像

问题描述

如何从带有外键用户的配置文件模型链接中获取图像。我尝试{% for user in users %}{{ user.profile_pic }}{% endfor %}使用 img src 这不显示图像。

class Profile(models.Model):

user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True)

profile_pic = models.ImageField(upload_to='ProfilePicture/', blank=True)

users = User.objects.exclude(id=request.user.id) 

标签: pythondjango

解决方案


我更像是烧瓶/SQLAlchemy 用户而不是 django 用户,但我相信原理非常相似。Profile是映射到数据库的模型,profile_pic是引用ImageField类的属性,并且您的模板文件应该有一个调用,而不是ImageField实例,而是对该实例的属性的调用,该实例存储图像文件的完整位置。因此,在您的示例中,调用将是这样的:

{% for user in users %}
<img src="{{ user.profile_pic.url }}">
{% endfor %}

我相信你也想使用filter而不是exclude在你的查询语句中,除非我误解了想要的结果。filter将为您提供 id 变量与当前用户的 id 匹配的模型。exclude将返回所有其他人,但不返回当前用户。


推荐阅读