Reputation: 97
I'm a newbie. I'm using Django to write a personal blog. I'm using CKEditor
to be able to insert images into my blog post. However, I want to show some first words of the posts on the homepage which does not include the images in the posts. I want to know if there is a way that I can get text only from RichTextField
in CKEditor
.
This is my current preview content:
I want it to be like this (no images):
This is my current code:
{% for post in post_list %}
<div class="card mb-4">
<div class="card-body">
<h2 class="card-title">{{ post.title }}</h2>
<p class="card-text text-muted h6">{{ post.Author }} | {{ post.created_on}} </p>
<p class="card-text">{{post.content|safe|truncatewords:20 }}</p>
<a href="{% url 'post_detail' post.slug %}" class="btn btn-primary">Read More →</a>
</div>
</div>
{% endfor %}
Upvotes: 0
Views: 1868
Reputation: 5405
The quickest way to do this would be Django's builtin striptags filter, like this:
<p class="card-text">{{post.content|striptags|safe|truncatewords:20 }}</p>
This will strip all HTML tags from your RichTextField, also removing any image tags. This will also remove any other tags though, like <strong>
, or <i>
.
If you want a more robust solution, you could look into django-bleach, a library for sanitizing TextFields like this. The way django-bleach works, is that you supply allowed tags (or use the default). django-bleach will then remove any other tags (and their content) from the field.
Upvotes: 5