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 content
s into truncated words.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With