[Django]-Newline in models.TextField() not rendered in template

73👍

linebreaks

Replaces line breaks in plain text with appropriate HTML; a single newline becomes an HTML line break (<br />) and a new line followed by a blank line becomes a paragraph break (</p>).

For example:

{{ value|linebreaks }}

6👍

Just a note, I was having a similar problem with newlines not showing up and I realized that when a TextField is declared as readonly, the text is wrapped with HTML paragraph tags:

<p> text </p>

as opposed to pre tags:

<pre> text </pre>

Pre tags preserve new line spaces, so if you do NOT make the field readonly, you will see the linespaces.

5👍

John, looks like you got a great answer from Ignacio. I just wanted to point out the steps that I took to use Ignacio’s answer for those who may be confused (like I was). Inside my template where I display the text field I added the “|linebreaks” behind the template field name (in my case a “job.desc”):

<ul>
    {% for job in varDataObject %}
    <li>
        <h4>
            <a href="#" onclick='funPath("Job", {{ job.id }})'>{{ job.title }} </a>
        </h4>
        Description: {{ job.desc|linebreaks }}
👤Greg

0👍

Saving text with newline (not \n) in your model’s TextField() using sql:

update event
set description='xyz
                asdasd
                 oaisjd '
where id=1;

In Django template:

{{ object.description|linebreaks }}
👤Aseem

Leave a comment