如何从 Django 模板中隐藏图像?

问题描述 投票:0回答:3

我正在尝试制作一个博客网站。在所有帖子页面上,它呈现数据库中的所有帖子。但并非所有帖子都有其特色图片。因此,我试图隐藏那些没有任何特色图像的图像部分。

这里是blog/model.py

class Article(models.Model):
STATUS_CHOICES = (
    ('draft', 'Draft'),
    ('published', 'Published'),
)
author = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.SET_NULL)
title = models.CharField(max_length=200)
slug = AutoSlugField(populate_from='title', unique=True, null=False, db_index=True)
excerpt = models.CharField(max_length=60)
featured_image = models.ImageField(upload_to="posts", null=True, blank=True, default="default.jpg")
content = FroalaField()
created = models.DateTimeField(auto_now_add=True)
last_update = models.DateTimeField(auto_now=True)
publish = models.DateTimeField(default=timezone.now)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')

这里是blog/view.py

# display all blog posts
def posts(request):
    all_posts = Article.published.all()
    context = {'all_posts': all_posts}
    return render(request, 'blog/posts.html', context)


# Single post
def single_post(request, slug):
    post = Article.objects.get(slug=slug)
    context = {
        'post': post,
    }
    return render(request, 'blog/single-post.html', context)

这里是blog/url.py

urlpatterns = [
    path('', views.posts, name="posts"),
    path('post/<slug:slug>/', views.single_post, name="single-post"),
]

这里是post.html

{% for post in all_posts %}
<li class="bg-white px-4 py-6 shadow sm:p-6 sm:rounded-lg">
  <article aria-labelledby="question-title-81614">
    <a href="{{ post.get_absolute_url }}">
      <!-- author details & option menus -->
      <div class="flex space-x-3">
        <div class="flex-shrink-0">
          <!-- author image -->
          <img
            class="h-10 w-10 rounded-full"
            src="{{ post.author.profile.avatar.url }}"
            alt=""
          />
        </div>
        <!-- author name and publish date time -->
        <div class="min-w-0 flex-1">
          <p class="text-sm font-medium text-gray-900">
            <a href="#" class="hover:underline">Dries Vincent</a>
          </p>
          <p class="text-sm text-gray-500">
            <time datetime="{{ post.publish.date }}"
              >{{ post.publish.date }}
            </time>
          </p>
        </div>
      </div>
      <div class="mt-4 space-y-4">
        {# show image if there is a feature image #}

        {% if post.featured_image.url %}

        <!-- article images -->
        <img
          class="object-cover w-full h-64 bg-center rounded-lg"
          src="{{ post.featured_image.url }}"
          alt="{{ post.title }}"
        />

        {% endif %}
      </div>
      <!-- article title -->
      <h1
        id="question-title-81614"
        class="mt-4 text-xl font-medium text-gray-900"
      >
        {{ post.title }}
      </h1>
    </a>
  </article>
</li>
{% endfor %}

这是为了更好地理解图片 post.html template page

django django-views django-templates
3个回答
0
投票

这看起来更像是一个错误的默认值,如果没有提供图像,您应该将其设置为

None
/
NULL
:

class Article(models.Model):
    # ⋮
    featured_image = models.ImageField(upload_to='posts', null=True, blank=True, default=None)

然后您可以使用如下条件渲染它:

{% if post.featured_image %}
    <!-- article images -->
    <img
        class="object-cover w-full h-64 bg-center rounded-lg"
        src="{{ post.featured_image.url }}"
        alt="{{ post.title }}"
    />
{% endif %}

您可以将

Article
default.jpg
设置为
None
,例如使用 Django shell 中的查询:

Article.objects.filter(
    featured_image='default.jpg'
).update(featured_image=None)

0
投票

定义模型时,

null=True
Blank=True
还将默认值设置为
None

如果您要渲染具有

featured_picture
的 Alf,则需要添加一些
post.featured_picture
,或者任何图像字段的名称,然后就可以开始了。


0
投票

{% if post.featured_image.url == "/media/default.jpg" %}

数据不存在 -->

{%其他%}

{{ post.featured_image.url }}

{% endif %}

© www.soinside.com 2019 - 2024. All rights reserved.