【发布时间】:2016-04-05 02:25:51
【问题描述】:
好的,所以我有一个显示图像的主页。这是从我的图像表中访问的。它包含所有者的一列,以用户 ID 的形式。我还有一张提交这些图片的用户表。如何使它在显示图像时使用 ID 从用户表中获取用户名?
views.py:
def index(request):
context = {}
populateContext(request, context)
context.update(gallery=ImageDoc.objects.only('thumbfile').order_by('-id'))
return render(request, 'register/index.html', context)
所以在 index.html 页面中,我可以遍历“图库”以显示图像。像这样:
{% for image in gallery %}
<a href="/logo/{{ image.slug }}">
<img src="{{ MEDIA_URL }}{{ image.largethumbfile }}">
{{ image.title }} by {{ image.username }} for {{ image.price }}
</a>
{% endfor %}
"image.username" 显然不起作用。我知道我需要通过以下方式访问 users 表:
get_users = User.objects.get()
并将抓取图像数据重新格式化为:
get_images = ImageDoc.objects.get()
但我不知道确保数据匹配的下一步。有任何想法吗?谢谢!
【问题讨论】:
-
{{ image.owner.username }} 不起作用?
-
试过了,没用。
-
如果您的模型对所有者使用外键,您应该能够访问它,但我通常不使用上下文更新路由,我更喜欢使用 render_to_response 并通过它传递我的查询。而且您必须在 {{ images.owner }} 上使用外键的名称
-
啊,是的,看来我有三张桌子。 images 表归 userprofile 表所有,而 userprofile 表又归 user 表所有。所以我用这个 {{ image.user.user.username }} 工作了!谢谢!
-
太棒了!很高兴能帮上忙!
标签: django django-templates django-views