我正在创建一个社交媒体页面,并且添加了以下功能:如果帖子字符大于50,则显示较短的版本,并在该位置附加“ ... more ”结束。
在我的models.py中,我有一个显示50个及更多字符的函数,我想在按下“ ... more ”时使用它。
当前,当按下时,文本会完全消失。
models.py:
class Post(models.Model):
file = models.FileField(upload_to='files/')
summary = models.TextField(max_length=600)
pub_date = models.DateTimeField(auto_now=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.user.username
def pub_date_pretty(self):
return self.pub_date.strftime('%b %e %Y')
def summary_pretty(self):
return self.summary[:50]
def summary_rem(self):
return self.summary[50:]
home.html
{% extends 'accounts/base.html' %}
{% block content %}
{% load widget_tweaks %}
{% load static %}
{% for post in posts %}
<div class="container pl-5">
<div class="row pt-3">
<img src="{% static 'rect.jpg' %}" width="600px" height="60px">
<div class="pt-3 pl-5" style="position: absolute;"> <b> {{ post.user.username }} </b> </div>
<br>
<div class="card" style="width: 600px;">
<img src="{{ post.file.url }}" width="599px">
</div>
<br>
<img src="{% static 'rect.jpg' %}" width="600px" height="150px">
<div class="col-6">
<script>
function addMore(e) {
e.innerText = "{{ post.summary_rem }}";
}
</script>
{% if post.summary|length > 50 %}
<div class="" style="position: absolute; bottom: 75px; left: 35px;"> <b> {{ post.user.username }} </b> {{ post.summary_pretty }} <span onclick="addMore(this)" style="cursor: pointer;" class="text-muted">...more</span> </div>
{% else %}
<div class="" style="position: absolute; bottom: 75px; left: 35px;"> <b> {{ post.user.username }} </b> {{ post.summary }} </div>
{% endif %}
</div>
</div>
</div>
<br>
<br>
<br>
{% endfor %}
{% endblock %}
已添加:
<script type="text/javascript">
function addMore(e) {
e.innerText = "{{ post.summary_rem }}";
}
</script>
{% if post.summary|length > 50 %}
<div class="" style="position: absolute; bottom: 75px; left: 35px;"> <b> {{ post.user.username }} </b> {{ post.summary_pretty }} <span onclick="addMore(this)" style="cursor: pointer;" class="text-muted">...more</span> </div>
{% else %}
<div class="" style="position: absolute; bottom: 75px; left: 35px;"> <b> {{ post.user.username }} </b> {{ post.summary }} </div>
{% endif %}