我有这个news_list.html
模板,它完整列出了所有文章。有什么方法可以将这些文章显示为整篇文章的快照。理想情况下,我想显示一个缩略图大小的图像,标题和前50个字符,并让用户单击文章以查看全部内容。能做到吗?如果可以,怎么办?
其他信息
这是我的模板(news_list.html):
{% extends 'base.html' %}
{% block title %}News{% endblock title %}
{% block content %}
{% for news in object_list %}
<div class="card">
<div class="card-header">
<span class="font-weight-bold">{{ news.title }}</span> ·
<span class="text-muted">by {{ news.author }} | {{ news.date }}</span>
</div>
<div class="card-body">
{% if news.thumb %}
<p align="center"><img src="{{ news.thumb.url }}" /></p>
{% endif %}
<p>{{ news.body | linebreaks }}</p>
</div>
<div class="card-footer">
{% if user.is_authenticated %}
<a href="{% url 'news_edit' news.pk %}">Edit</a>
<a href="{% url 'news_delete' news.pk %}">Delete</a>
{% endif %}
</div>
</div>
<br />
{% endfor %}
{% endblock content %}
models.py
class News(models.Model):
title = models.CharField(max_length=255)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE,
)
thumb = models.ImageField(blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('news_detail', args=[str(self.id)])
views.py
class NewsListView(ListView):
model = News
template_name = 'news_list.html'
class NewsDetailView(DetailView):
model = News
template_name = 'news_detail.html'
login_url = 'login'
class NewsUpdateView(LoginRequiredMixin, UpdateView):
model = News
fields = ('title', 'body', 'thumb')
template_name = 'news_edit.html'
login_url = 'login'
def test_func(self):
obj = self.get_object()
return obj.author == self.request.user
class NewsDeleteView(LoginRequiredMixin, DeleteView):
model = News
template_name = 'news_delete.html'
success_url = reverse_lazy('news_list')
login_url = 'login'
def test_func(self):
obj = self.get_object()
return obj.author == self.request.user
class NewsCreateView(LoginRequiredMixin, CreateView):
model = News
template_name = 'news_new.html'
fields = ('title', 'body', 'thumb')
login_url = 'login'
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
答案 0 :(得分:0)
我在模板的body元素中添加了truncatewords
:
{% block content %}
{% for news in object_list %}
<div class="card" style="width:300px">
<div class="card-header">
<span class="font-weight-bold">
<a href="{% url 'news_detail' news.pk %}" style="color:black">{{ news.title }}</a>
</span> ·
<span class="text-muted">by {{ news.author }} | {{ news.date }}</span>
</div>
<div class="card-body">
{% if news.thumb %}
<p align="center"><img src="{{ news.thumb.url }}" /></p>
{% endif %}
<p>{{ news.body | linebreaks | truncatewords:30 }}
<a href="{% url 'news_detail' news.pk %}">Full story</a></p>
</div>
<div class="card-footer">
{% if user.is_authenticated %}
<a href="{% url 'news_edit' news.pk %}">Edit</a>
<a href="{% url 'news_delete' news.pk %}">Delete</a>
{% endif %}
</div>
</div>
<br />
{% endfor %}
{% endblock content %}