John Eipe
John Eipe

Reputation: 11226

newline in models.TextField() not rendered in template

I have a model with an attribute,

desc = models.TextField()

I entered data using admin interface provided by Django and then later viewed my template where the database values are fetched and displayed.

In my admin interface I left newline (just by leaving blank lines in between my paragraphs) but they are displayed as a single paragraph in my template.

I'm using Django 1.3 and MySQL.

Upvotes: 34

Views: 25400

Answers (4)

Aseem
Aseem

Reputation: 6787

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 }}

Upvotes: 0

Greg
Greg

Reputation: 51

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 }}

Upvotes: 5

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798944

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 }}

Upvotes: 75

Einstein
Einstein

Reputation: 441

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.

Upvotes: 6

Related Questions