You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用Django模板实现首页精选文章的自动更新?

方案1:无需新增字段,直接取最新两篇(最简实现)

不用修改模型,直接在视图中查询最新发布的2篇文章,传给模板即可,完全不用手动操作。

视图代码调整

  • 如果你用的是类视图(ListView):
from django.views.generic import ListView
from .models import Post

class PostListView(ListView):
    model = Post
    template_name = '你的模板路径.html'
    context_object_name = 'object_list'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # 按发布时间倒序,取前2篇作为精选
        context['featured_posts'] = Post.objects.order_by('-pub_date')[:2]
        return context
  • 如果你用的是函数视图:
from django.shortcuts import render
from .models import Post

def post_list(request):
    object_list = Post.objects.all()
    # 按发布时间倒序筛选最新2篇
    featured_posts = Post.objects.order_by('-pub_date')[:2]
    return render(request, '你的模板路径.html', {
        'object_list': object_list,
        'featured_posts': featured_posts
    })

模板新增精选板块

在首页模板里添加以下代码:

<h3>精选文章</h3>
<ul>
{% for post in featured_posts %}    
    <li><a href="{% url 'article_detail' pk=post.pk %}">{{ post.title }}</a> - {{ post.author.first_name }} {{ post.author.last_name }}<br/>
    {{ post.summary }}<br/>{{ post.adventure_date }}</li>
{% endfor %}
</ul>

方案2:用featured字段自动维护(适合需标记精选的场景)

如果你一定要用featured = BooleanField(default=True)字段,可以重写模型的save方法,每次新增文章时自动调整状态,始终保持最新的2篇为精选:

模型代码修改

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    summary = models.TextField()
    adventure_date = models.DateField()
    pub_date = models.DateTimeField(auto_now_add=True)  # 若无发布时间字段则新增,用来排序
    featured = models.BooleanField(default=True)

    def save(self, *args, **kwargs):
        # 先保存当前文章
        super().save(*args, **kwargs)
        # 按发布时间倒序获取所有文章
        all_posts = Post.objects.order_by('-pub_date')
        # 仅保留前2篇为精选,其余自动取消
        for idx, post in enumerate(all_posts):
            if idx >= 2 and post.featured:
                post.featured = False
                post.save(update_fields=['featured'])
            elif idx < 2 and not post.featured:
                post.featured = True
                post.save(update_fields=['featured'])

视图与模板用法

视图中获取精选文章:

context['featured_posts'] = Post.objects.filter(featured=True).order_by('-pub_date')

模板代码和方案1完全一致。

注意:如果没有pub_date字段,可替换成adventure_date或其他时间字段来排序,把代码里的-pub_date改成对应的字段名即可。

内容的提问来源于stack exchange,提问作者indigold

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 02:15:14