Как скрыть изображение из шаблона Django?
Я пытаюсь сделать сайт-блог. На странице всех постов отображаются все посты из базы данных. Но не все посты имеют свое изображение. Поэтому я пытаюсь скрыть те разделы с изображениями, которые не имеют характерных изображений.
Вот 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
Это больше похоже на неправильное значение по умолчанию, если изображение не предоставлено, вы должны установить его на 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:
Article.objects.filter(
featured_image='default.jpg'
).update(featured_image=None)
При определении модели null=True
и Blank=True
также установите значение по умолчанию None
.
Если вы собираетесь рендерить Alf те, у которых есть featured_picture
, вам нужно добавить немного if post.featured_picture
, или как там называется ваше поле изображения, и все готово.