Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rendering of textfield and charfield chomps out extra whitespace (Django/Python)

I've noticed that my template is rendering my model.CharField and model.TextField without any excess whitespace.

For example, if I enter data such as...

This     is a           test


to see what  happens.

The rendered object field will appear as...

This is a test to see what happens.

Is this an intentional feature of Django or have I missed some filter or parameter somewhere?

I've checked the field itself with some debug code (print object.field) and it does contains the extra whitespace, so the problem is in the rendering side.

How can I allow the user to enter paragraphs of data in TextFields? How can I preserve the whitespace that the user may have entered?

like image 916
powlo Avatar asked Feb 01 '12 11:02

powlo


1 Answers

As you can see even in StackOverflow your spaces do not display, this is from the source of your question:

This     is a           test


to see what  happens.

Will save in the database as:

This     is a           test\n\n\nto see what  happens.

You have to problems when rendering as html:

  1. Extra spaces between words are stripped on display by the browser, unless it is between <pre></pre> tags

  2. Linebreaks will be rendered as plain text linebreaks, which do not display in the browser unless between <pre></pre> tags.

For spaces, you can use such a template filter to replace them with their html entity equivalent: &nbsp;.

To convert database linebreaks in HTML linebreaks, use linebreaksbr built-in filters. For example, if {{ foo }} is: test\nbar, then {{ foo|linebreaksbr }} will render: test<br />bar

  1. Create a "templatetags" folder in some of your apps with an __init__.py file in it.

  2. Save the snippet for example in someapp/templatetags/replace_tag.py

  3. Load the template filter in the template as such {% load replace_tag %}

  4. Combine replace and linebreaksbr as such: {{ foo|linebreaksbr|replace:" ","&nbsp;" }}

You can also make your own template filter that will process the text into the HTML you need. In any case, refer to the custom template filter documentation for complete information.

like image 188
jpic Avatar answered Sep 21 '22 23:09

jpic