在 Django 中切片 TextField() 的内容

Slicing the content of a TextField() in Django

我正在开发一个 Django 博客,有一个 html 页面,博客条目显示在它们的标题和日期旁边。但是此页面上的博客条目应该是摘要(实际博客的前 700 个字符 body)。所以,有一个名为 'Post' 的模型,带有 'title, 'date' 和 'body' objects 但问题是获取 'body' [= 的前 700 个字符34=] 在所有博客条目的视图中显示。在遍历 Post.objects.all() 之后,视图中仅显示最后一个博客条目内容(700 个字符)。我的数据库中有 4 个博客条目。同时,当我 运行 print(desc) 时,我在终端中得到了我想要的确切结果。这是代码。

models.py

class Post(models.Model):
     title = models.CharField(max_length=140) 
     body = models.TextField()  
     date = models.DateTimeField()
 
     def __str__(self):
         return self.title 

views.py

def body_summary(request):
        gen = Post.objects.all().order_by("-date")[:25]
         for summary in gen:
               desc = summary.body[:700]
               print(desc)
         return render(request, 'blog/blog.html', {'gen': gen, 'desc': desc})

blog.html

{% for post in gen %}
<h5 > {{ post.date|date:"Y-m-d" }}  <a href="/blog/{{ post.id }}">{{ post.title }}</a> </h5>
 <h6 >{{ desc }} <a href="/blog/{{ post.id }}">[...]</a></h6>

{% endfor %}

问题是您在每次迭代期间都更新了 desc 变量。 desc 变量仅包含最后一个博客条目的内容,因为它是最后一个迭代元素。

您应该有一个列表并在每次迭代期间将前 700 个字符附加到它并在 html 中使用它或将 summary.body 直接更改为 summary.body[:700](即)summary.body = summary.body[:700].

将您的 views.pyblog.html 更改为

views.py

def body_summary(request):
        gen = Post.objects.all().order_by("-date")[:25]
         for summary in gen:
               summary.body = summary.body[:700]
         return render(request, 'blog/blog.html', {'gen': gen})

blog.html

{% for post in gen %}
<h5 > {{ post.date|date:"Y-m-d" }}  <a href="/blog/{{ post.id }}">{{ post.title }}</a> </h5>
 <h6 >{{ post.body }} <a href="/blog/{{ post.id }}">[...]</a></h6>

{% endfor %}

不需要在视图中迭代来执行此操作,您可以简单地使用 truncatechars template filter [Django docs] 来执行此操作(或者如果正文是 HTML,您可以使用 truncatechars_html):

def body_summary(request):
    gen = Post.objects.all().order_by("-date")[:25]
    return render(request, 'blog/blog.html', {'gen': gen})

现在在模板中:

{% for post in gen %}
    {{ post.body|truncatechars:700 }}
{% endfor %}