Django:如何在图像模型中显示所有图像

Django:如何在图像模型中显示所有图像,django,django-models,django-templates,django-views,Django,Django Models,Django Templates,Django Views,我正在尝试显示与当前所选用户关联的所有图像 这是基于这个已解决的问题: 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.

我正在尝试显示与当前所选用户关联的所有图像

这是基于这个已解决的问题:

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)
模板>索引_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>
<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>

#测试,看看它是否工作,如果没有 {{user.images.image} #理想溶液 {%if user.images.images%} {user.images%中img的%s}
{%endfor%} {%else%} 没有图像

{%endif%}


您提供的代码无法满足您的需要。下面是一个可能会:

示例

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>
    # 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>
<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>

#理想溶液 {%if图像%} {图像中img的百分比%}
{%endfor%} {%else%} 没有图像

{%endif%}


希望这有帮助

请澄清您的具体问题或添加其他详细信息,以突出显示您所需的内容。正如目前所写的,很难准确地说出你在问什么。好吧,if语句看起来很有效,因为我不再得到“无图像”但没有图像显示。有什么好的调试方法吗?呃,检查一下你的django管理员你是否有任何图像,而且我也不完全确定这是否是显示图像的方式(
img.url
),也许可以研究一下吗?@AlexWinkler刚刚用
img.image.url
img.image.path
做了一个快速的研究,希望这能有所帮助!是的,我有几个与这个用户相关的图像。此外,我有媒体URL和静态文件工作。在扩展用户配置文件中,我添加了图像字段,我可以使用user.profile.image.url通过该字段显示图像。所以奇怪的是,我还有媒体URL和静态文件。在扩展用户配置文件中,我添加了图像字段,我可以显示字段user.images.image.url不起作用。我希望升级投票,但首先需要更多代表。等我有了它就行了。再次感谢!