How to use linebreak in Django templates - django

Hi I am new to python Django.
I want new line in specific places, So I tried
def abc(request):
text = "This is\n a good example"
return render(request, 'test.html', {'text' : text})
In HTML part
Hello {{ text|linebreaks }}
And this is working perfectly fine with output
Hello This is
a good example
Here is my question
I store some 400 - 800 words in my database which has approximately 4-5 paragraph.
I want to new line here.
So, I store data like "This is\n a good example" in my database.
And simply call it in django template(Html side)
but it prints
Hello This is\n a good example
In here why line break is not working?
My HTML true code
{% for essay in eassays %}
{{ essay.description|linebreaks }}
{% endfor %}
I have changed name. Also, I am loading 100 such data.
Any possible solution or other logic!
Thankyou!

So, I store data like "This is\n a good example" in my database.
You likely stored '\\n' in the database, so a backslash, followed by an n. Not a new line chacter '\n' [wiki]. Note that if you write \n in a form element, then it will be escaped and thus stored accordingly.
It might be better to use a <textarea> in your form elements to let users use new lines (by pressing Enter).
You can try to fix the damage by substituting the strings, with:
from django.db.models import Replace, Value
Essay.objects.update(
description=Replace('description', Value('\\n'), Value('\n'))
)
and thus update your database such that '\\n' is now replaced by '\n'.

Related

Trying to render a django form field as a variable in a script tag in an html template, but the javascript isn't working

My issue is simple enough--I am trying to render a form field from a django form into a javascript variable, defined within a <script> tag, within a django template.
When I output a CharField, there's no problem. But when I try to render a ChoiceField, the resulting output breaks the html, and prevents the script tag from correctly parsing my variable.
To demonstrate my setup, I have a form defined in forms.py, exactly like this example form:
from django import forms
form = TestForm(forms.Form):
testfield = forms.ChoiceField(initial="increase_rate",
choices=[
("a", "option a"),
("b", "option b"),
("c", "option c"),
("d", "option d")
])
I am instantiating the form in views.py, and passing it into a django template to be rendered.
from django.shortcuts import render
from .forms import TestForm
[...]
#require_http_methods(["GET"])
def webpage(request):
form = TestForm()
return render(request, 'index.html', {"form":form})
Then, finally, in my template, I have something like the following:
[...]
<script>
window.testfield = '{{ form.testfield }}'
</script>
[...]
Up until this point, everything works perfectly. No trouble at all. But when I render the field into the template, and inspect it in my browser, I get the following:
<script>
window.testfield = '<select name="trigger" id="id_trigger">
<option value="a" selected>option a</option>
<option value="b">option b</option>
<option value="c">option c</option>
<option value="d">option d</option>
</select>'
</script>
This output breaks the html, and prevents the script tag from being interpreted as a variable like I want. This is a major problem, because I want to reuse these programmatically elsewhere on the page.
I tried the following:
<script>
window.testfield = '{{ form.testfield|escape }}'
</script>
But was still unsuccessful. Any help anyone can give would be greatly appreciated!
I am actively researching a solution. My current guess is that the output needs to be escaped somehow that I don't understand. I figure the template tags and filters have my answer, I just have to find it. Will post an update once a solution is found.
Use <script type="text/template"></script>.
This way the browser knows it's just text and will ignore it.
So, I figured it out. Turns out that the issue was that the presence of white space, line breaks, and unescaped double quotes (") were breaking the tag when it was parsed at HTML.
So I ended up using the following:
{% spaceless %}
<script>
window.testfield = '{{ form.testfield|addslashes }}'
</script>
{% endspaceless %}
And it worked, allowing me to store the string representation of the django form field in a javascript variable. As per the documentation, the {% spaceless %} "Removes whitespace between HTML tags. This includes tab characters and newlines." [1]. As for the filter |addslashes, it "Adds slashes before quotes. Useful for escaping strings in CSV" [2]. In my case, both solutions were needed, as without either of them, the script tag broke.
As for why the |escape filter didn't work on it's own, I'm not sure. Reading the documentation, it seems like it probably should have. The following is what the |escape filter actually does [3]:
Escapes a string’s HTML. Specifically, it makes these replacements:
< is converted to <
> is converted to >
' (single quote) is converted to '
" (double quote) is converted to "
& is converted to &
I can only guess why this didn't work. I figure it's because it didn't do anything about the white space. But I shouldn't speculate. I welcome any explanations you might have. As ever, understanding the way the machine thinks is better than any single, specific solution. Thanks.
[1] - https://docs.djangoproject.com/en/dev/ref/templates/builtins/#spaceless
[2] - https://docs.djangoproject.com/en/dev/ref/templates/builtins/#addslashes
[3] - https://docs.djangoproject.com/en/dev/ref/templates/builtins/#escape

How to preseve newline in django posts without using a WYSIWYG editor?

I am using django's forms class along with it's cleaned_data method to get user posts/comments. The problem is that the newlines are not preserved in the cleaned_data field so
The firs line of comment.
And the second lines.
Ends up being
The firs line of comment. And the second lines.
Which is not good.
How to avoid this without using a WYSIWYG editor?
If you're referring to the output of the value held in the field, you just need to use the linebreaks or linebreaksbr filter: https://docs.djangoproject.com/en/1.7/ref/templates/builtins/#linebreaks
{{ instance.field|linebreaks }}
or
{{ instance.field|linebreaksbr }}
to get the correct formatting without having to use a wysiwyg editor.

How to write multi line input in Django

I am making a very basic BBS system (like blog) in Django.
I've made a form where user can type in their content which I call 'body' and I declare it as
folowing in the forms.py:
body = forms.CharField(widget= forms.Textarea, label="body",required=True)
and in the models.py,
body = models.TextField()
I somehow can't seem to be able to write multi line texts...
To sum it up,
I can write multiple lines into my form like:
Hello this is test
This is sample test2
333333
But When I submit it,
I only see
Hello this is test This is sample test2 333333
The error happened when display it.
Textarea uses cr\lf to break lines. That is how it would
be saved into db. But html will ignore cr\lf you need to replace cr\lf with <br> or <p>
A template tag linebreaks can help you, when you display it.
{{ value|linebreaks }}

django template string - replace line break with line space

I have a string in my django1.4 template that I want to replace the line breaks with a whitespace. I only want to replace the line breaks with a single white space in the template string.
So far all my searces on django docs, Google and SO have not given me an answer.
Here is my string in my template:
{{ education_detail.education_details_institution_name|safe|truncatechars:20|striptags }}
When I have the following string saved:
University
Bachelor of Something
2008 - 2010
The string in the django template is rendered as:
UniversityB...
I want to replace the line break with a space between the yB like so:
University B...
How would I do this?
Here is the custom filter code that I finally got operational:
from django import template
register = template.Library()
#register.filter(name='replace_linebr')
def replace_linebr(value):
"""Replaces all values of line break from the given string with a line space."""
return value.replace("<br />", ' ')
Here is the call on the template:
{{ education_detail.education_details_institution_name|replace_linebr }}
I hope that this will help somebody else.
You can rely on built-in truncatechars filter's behavior to replace newlines with spaces. All you need is to pass a length of the string as an argument, so that you would not see your string shortened:
{% with value|length as length %}
{{ value|truncatechars:length }}
{% endwith %}
This is a bit hacky, but uses only built-in filters.
You can always write a custom filter if you need this kind of functionality to be reusable.

Is is possible to html encode output in AppEngine templates?

So, I'm passing an object with a "content" property that contains html.
<div>{{ myobject.content }}</div>
I want to be able to output the content so that the characters are rendered as the html characters.
The contents of "conent" might be: <p>Hello</p>
I want this to be sent to the browser as: &amplt;p&ampgt;Hello&amplt;/p>
Is there something I can put in my template to do this automatically?
Yes, {{ myobject.content | escape }} should help (assuming you mean Django templates -- there's no specific "App Engine" templating system, GAE apps often use the Django templating system); you may need to repeat the | escape part if you want two levels of escaping (as appears to be the case in some but not all of the example you supply).
This is Django's django.utils.html.escape function:
def escape(html):
"""Returns the given HTML with ampersands, quotes and carets encoded."""
return mark_safe(force_unicode(html).replace('&', '&').replace('<', '&l
t;').replace('>', '>').replace('"', '"').replace("'", '''))
Also, see here.