Search code examples
pythonhtmldjangowysiwygsummernote

"Read More" for Django WYSIWYG editor


I am using django-summernote editor for creating posts with text and images which are saved in a character field as HTML tags.

I want to add a read-more functionality where a limited sized preview is shown for all the posts. An idea could be to truncate the character field, but it may lead to truncation of HTML image tags if they happen to be positioned between the boundary.

How to get around this?


Solution

  • Django has two template filters you can use to make sure your HTML doesn't get malformed: truncatechars_html and truncatewords_html

    Template filters are just functions, so you can import them anywhere you need in your Python code and assign the result to a variable you can use elsewhere, etc.

    Example:

    from django.template.defaultfilters import truncatechars_html
    
    html = """<p>Look, I&#8217;m some HTML. You can truncate me
           with Django template filters</p>"""
    truncated_value = truncatechars_html(html, 30)