Вьюха
@register.inclusion_tag('blog/category_list.html')
def get_category_post ():
categories = (
Category.objects.all()
)
context = {
'categories': categories,
}
return (context)
Темплейт
{% for category in categories %}
<div class="row">
<div class="col-md-12">
<div class="section-title">
<h2 class="title"> {{category.title}} </h2>
</div>
</div>
{% for post in category.posts.all %}
<div class="col-md-4">
<div class="post post-sm">
{% if post.photo %}
<a class="post-img" href="{{ post.get_absolute_url }}"><img src="{{post.photo.url}}" alt="" class="mr-3"></a>
{% else %}
<a class="post-img" href="{{ post.get_absolute_url }}"><img src="https://picsum.photos/seed/picsum/350/300" alt="lalala" class="mr-3"></a>
{%endif%}
<div class="post-body">
<div class="post-category">
<a href="category.html">{{post.title}}</a>
</div>
<h3 class="post-title title-sm"><a href="{{ post.get_absolute_url }}">{{post.descriptions|safe}}</a></h3>
<ul class="post-meta">
<li><a href="author.html">{{ post.author }}</a></li>
<li>{{ post.created_at }}</li>
</ul>
</div>
</div>
</div>
{% endfor %}
<!-- /post -->
</div>
Модели
<code>class Post(models.Model):
title = models.CharField(max_length=255, verbose_name='Название')
descriptions = models.CharField (default='Some descriptions',max_length= 150, verbose_name='Короткое описание')
slug = models.SlugField(max_length=255, verbose_name='URL_Поста', unique=True)
author = models.CharField(max_length=100, verbose_name='Автор')
content = models.TextField(blank=True,verbose_name='Контент')
created_at = models.DateTimeField(auto_now=True, verbose_name='Опубликована:')
photo = models.ImageField(upload_to='photo/%Y/%m/%d/',blank=True, verbose_name='Фото')
views = models.IntegerField(default=0, verbose_name='Количество просмотров:')
tags = models.ManyToManyField(Tag, blank=True, related_name='tags')
categories = models.ManyToManyField(Category, related_name='posts')</code>
<!-- /row -->
{% endfor %}