I am green in Django.

I want to make a user input field on the site. After that, the text is saved in the database. And output to the template. The problem is that the text will be stored continuously in the model without formatting (at least a line break, I'm not talking about italics, etc.) and, accordingly, displayed in a template with solid text.

Tell me how to solve this problem? How to take into account the line breaks made by the user when outputting to the template?

Threats Manipulations with html in TextField and the safe filter will not work; BBcode option, but then the question arises how to make a forum text input form with formatting buttons?

  • the issue with the transfer is decided through {{value | linebreaks}} - FlatOMG

1 answer 1

The simplest is to use any advanced text editor for django. For example, django-ckeditor . It has a built-in field that helps you filter unnecessary html tags. Plus there is the html editor itself, the database stores html. In general, there is everything in the help

The second option is to use the bleach package and manually filter the tags. It can also be used with any add-on, like markdown . Of the minuses here - you have to write your own handler for these tags. Code example:

# templatetags/comments.py # -*- coding: utf-8 -*- import bleach import markdown def markdown_comment(value): return bleach.clean( markdown.markdown(value, extensions=['nl2br']), strip=True, tags=['strong', 'p', 'blockquote', 'br']) @register.filter def comment_markdown(value): return mark_safe(markdown_comment(value)) 

Well, then use as {{ value|comment_markdown }}