34

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.

4 Answers 4

76

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

Sign up to request clarification or add additional context in comments.

4 Comments

This works for rendering, but what if you want to keep the \n for javascript, input values, or emails?
Hi, I am also looking for the same, I have a model with text field and also corresponding admin class, I have no clue where to put this ??? do we need to override the html and create a template for it???
@Mike forgot to put his beak into this one stackoverflow.com/a/1894945
Such a simple solution! Works for DetailView too.
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.

Comments

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

2 Comments

This answer could probably be a comment on Ignacio's answer
Thanks caulitomaz! How do I repair the situation?
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 }} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.