【问题标题】:Django how to limit template to only two postsDjango如何将模板限制为只有两个帖子
【发布时间】:2021-04-03 15:43:15
【问题描述】:

我只想显示模板上添加的最后两个帖子(最好是今天发布的帖子),我已经看到这样做了,但不是基于类的视图。

from .forms import PostForm
from .models import Post
from django.views.generic import ListView
from django.views import generic
from django.urls import reverse_lazy


class homeView(ListView):
    model = Post
    template_name = 'MAG-page.html'

MAG-page.html

{% for post in object_list %}
      <div class="col-lg-6 col-md-12">


        <div>
        <!--Image-->
        <div class="view overlay rounded z-depth-1-half mb-3">
          <img src="{{post.Thumbnail.url}}" class="img-fluid" >
          <a>
            <div class="mask rgba-white-slight"></div>
          </a>
        </div>

        <!--Excerpt-->
        <div class="news-data">
          <a href="" class="light-blue-text">
            <h6>
              <i class="fas fa-plane"></i>
              <strong> {{post.author}}</strong>
            </h6>
          </a>
          <p>
            <strong>
              <i class="far fa-clock"></i> {{post.Date}}</strong>
          </p>
        </div>
        <h3>
          <a>
            <strong>{{post.title|safe}}</strong>
          </a>
        </h3>
        <p> {{post.Text|safe}}</p>
        </div>
{% endfor %}

【问题讨论】:

标签: django


【解决方案1】:

只需添加一个查询集并将其限制为 2 个对象。

class YourView(ListView):
    queryset = Post.objects.order_by('-date')[:2] # replace 'date' if it does not match your case
    # other attributes/methods

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-02
    • 2022-11-12
    • 1970-01-01
    • 2010-11-12
    • 2019-10-23
    • 2022-01-11
    • 1970-01-01
    • 2011-03-11
    相关资源
    最近更新 更多