18

I have text saved in a database record that looks like this.

This is the text

This is on a new line with a space in between

When I output it on the Django template, it comes out like this

This is the text This is on a new line with a space in between

How can I output the text on my django template to reflect the way it appears in the database?

1
  • use <br> after {{text|linebreaks}} Commented Feb 10, 2016 at 8:13

4 Answers 4

26

Use linebreaks or linebreaksbr filter:

{{ text|linebreaks }}

Or surround the text with <pre>...</pre>.

<pre>{{ text }}</pre>
Sign up to request clarification or add additional context in comments.

Comments

3

I linebreaks uses <p> tag to convert new line, this will probally not preserve the empty line or you will just not see it due to css styling. You can try instead linkebrksbr that will use <br/> for new lines.

Hope this helps

Comments

1

<pre> tag works fine, but has some default declarations (like monospace and margins).

The solution for me was to take the essence of the <pre> tag - the following declaration:

white-space: pre;

And modify it (if you don't need extra spaces):

white-space: pre-line;

Now the data from the database fields models.TextField keep all the line breaks.

Comments

0

Try to use <br/>

<br/> is an HTML code. Don't forget you are working with HTML using Django. Keeping this in mind will solve a lot of beginners trouble.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.