【问题标题】:How to Display Data According to Different Different category on Page in Django?如何在 Django 中根据页面上不同的类别显示数据?
【发布时间】:2020-09-03 21:19:27
【问题描述】:

我的数据库中有多个类别商店,我正在开发一个博客网站,我想根据我的要求显示首页。 首页上有很多可用的版块,每个版块都有不同的类别,因此数据将按类别显示。请让我知道我该怎么做。

这是我的views.py文件......

def article_list(request):
category = Category.objects.all().order_by('created_at')
blog = Post.objects.all().order_by('-created_at')[0:5]
return render(request, 'article/index.html',
              {'category': category, 'blog': blog})

这是我关于 index.html 文件的一个部分...我想在这部分从business 类别(这是存储在我的数据库中)获取数据。但是我正在从数据库中获取所有帖子,请告诉我如何更改我的for loop,以便从business 类别中显示数据。

<ul class="list-posts">
                                        {% for i in blog %}
                                        <li>
                                            <img src="/media/{{i.image}}" alt="">
                                            <div class="post-content">
                                                <h2><a href="single-post.html">{{i.name}}</a></h2>
                                                <ul class="post-tags">
                                                    <li><i class="fa fa-clock-o"></i>{{i.created_at}}</li>
                                                </ul>
                                            </div>
                                        </li>
                                        {% endfor %}
                                    </ul>

【问题讨论】:

    标签: django python-3.x django-rest-framework django-views django-templates


    【解决方案1】:

    你还没有发布你的模型是如何声明的,所以我假设是这样的:

    class Category(models.Model):
        name = models.CharField(max_length=80)
    
    class Post(models.Model):
        name = models.CharField(max_length=80)
        category = models.ForeignKey(Category, on_delete=models.CASCADE)
        image = models.ImageField(upload_to='posts')
        created_at = models.DateTimeField(auto_now_add=True)
    

    您可以在模板中使用{% if %} 标签限制帖子:

    <ul class="list-posts">
        {% for post in blog %}
        {% if post.category.name == 'business' %}
        <li>
            <img src="/media/{{ post.image }}" alt="">
            <div class="post-content">
                <h2><a href="single-post.html">{{ post.name }}</a></h2>
                <ul class="post-tags">
                    <li><i class="fa fa-clock-o"></i>{{ post.created_at }}</li>
                </ul>
            </div>
        </li>
        {% endif %}
        {% endfor %}
    </ul>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-02
      • 2018-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-12
      • 1970-01-01
      相关资源
      最近更新 更多