将上传的项目显示到 django 的网格中(html 和 css)

display uploaded items to a grid on django(html and css)

我有一个网格,必须在 3 列中显示上传的图像,我第一次尝试这个时,我意识到只显示了第一张上传的图像,所以我添加了一个 forloop 计数器,它也能正常工作。我应该怎么做才能在网格上显示这些上传的图像。

views.py

  def profile(request, username=None):
  profile, created = Profile.objects.get_or_create(user=request.user)
if username:
    post_owner = get_object_or_404(User, username=username)
    user_posts = Post.objects.filter(user_id=post_owner)

else:
    post_owner = request.user
    user_posts = Post.objects.filter(user=request.user)

args1 = {
    'post_owner': post_owner,
    'user_posts': user_posts,
}
return render(request, 'profile.html', args1)

models.py

    class Post(models.Model):
        images = models.FileField(upload_to='clips', null=True, blank=True)
        user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default='username')

        def __str__(self):
            return str(self.text)

html

    {% for Post in user_posts %}
      <div class="grid-wrapper">
        {% if forloop.counter|divisibleby:3 %}
          <div class="grid-item">
            {% if Post.video %}
              <video width="400" style="border-radius: 2px;">
                <source src='{{ Post.video.url }}' type='video/mp4'>
              </video>
            {% endif %}
          </div>
        {% endif %}
      </div>
    {% endfor %}

css

    .grid-wrapper {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        grid-auto-rows: 250px;
        grid-gap: 1rem;
        grid-auto-flow: row;
    }

    .grid-item {
        background: red;
        display: flex;
        justify-content: center;
        align-items: center;
    }

你能试试这个吗?这会起作用。

<div class="grid-wrapper">
  {% for Post in user_posts %}
    <div class="grid-item">
      {% if Post.video %}
      <video width="400" style="border-radius: 2px;">
        <source src='{{ Post.video.url }}' type='video/mp4'>
      </video> 
      {% endif %}
    </div>
  {% endfor %}
</div>