Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

python - Django Change Variable From DataBase on Referencing

I'm currently learning Django and I wanted to start off with a really simple blog app. I have a model for my post:

class Post(models.Model):

    title = models.CharField(max_length=200)
    author = models.ForeignKey(
        'auth.User',
        on_delete=models.CASCADE,
    )
    body = models.TextField()

Then I'm referencing it on my home page template:

{% extends 'base.html' %} 

{% block content %} 

{% for post in object_list %}

<div class="post-entry">
  <h2><a href="{% url 'post_detail' post.pk %}">{{post.title}}</a></h2>
  <p>{{post.body}}</p>
</div>

{% endfor %} 

{% endblock content %}

I would like to make post.body to be only first 50 or so characters but post.body[:50] returns syntax error. How could I do that?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try This:-

You can use {{ post.body|truncatechars:50 }} for this.

It will display only 50 characters of your Post Body

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...