我正在尝试显示与当前所选用户相关联的所有图片
这是基于这个已解决的问题:django upload to image model with foreign key to user
Model.py
class Images(models.Model):
image = models.ImageField(upload_to='profile_image', null=True, default='profile_image/none/no-img.png')
user = models.ForeignKey(User, on_delete=models.CASCADE)
Views.py
@login_required
def index_account(request):
args = {'user': request.user }
return render(request, 've/cp/index_account.html', args)
模板> index_account.html
<p><a href="{% url 've:edit_images' %}">Edit your images</a></p>
# test to see if it worked w/o if
{{ user.images.image}}
# ideal solution
{% if user.images.images %}
{% for img in user.images %}
<img src="{{ user.images.image.url }}"><br>
{% endfor %}
{% else %}
<p>No images</p>
{% endif %}
<br>
<hr>
答案 0 :(得分:1)
您提供的代码无法满足您的需求。所以这里有一个可能的例子:
示例强>
views.py
from app_name.models import Images
@login_required
def index_account(request):
images = Images.objects.filter(user=request.user)
return render(request, 've/cp/index_account.html', {"images": images})
index_account.html
<p><a href="{% url 've:edit_images' %}">Edit your images</a></p>
# ideal solution
{% if images %}
{% for img in images %}
<img src="{{ img.url }}"><br>
{% endfor %}
{% else %}
<p>No images</p>
{% endif %}
<br>
<hr>
希望这有帮助!