Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is There A Way to Truncate by Words in View in Django?

I made a JSON serializer to view. I returned a QuerySet object which is called entries which looks for POST argument as below:

entries = blog.models.Entry.objects.filter(content__icontains=request.POST.get('q'))

Then I used serializers from django.core.

serializers.serialize("json", entries, fields=('title', 'content', 'created'))

This works like a charm, however, I want to return contents into truncated words.


Environment

  • Django 1.8.7
  • Python 3.4
like image 352
Eray Erdin Avatar asked Jan 22 '16 13:01

Eray Erdin


1 Answers

You can use the Truncator class from django.utils.text, for example:

from django.utils.text import Truncator
my_text = "Lorem ipsum dolor sit amet"
n_words = 3
truncated_text = Truncator(my_text).words(n_words)
print(truncated_text)
# Lorem ipsum dolor...

Truncator can also truncate to a number of characters, and can parse HTML as well as plain text. While official docs appear to missing, the source code is pretty senf-explanatory, see: https://github.com/django/django/blob/master/django/utils/text.py

like image 102
Dave Avatar answered Oct 16 '22 14:10

Dave