How to show code snippet in django template, "|safe" filter not helps - django

I'm trying to make app like gist.github.com. After saving code snippets they looks in like long string. I tried different filters like "safe, escape ... etc". Nothing helped me.
In database code looks like:
def asd(a):
return a+2
asd(2)
This is my template code:
<div>{{ s.code|escape }}</div>
Result is:
def asd(a): return a+2 asd(2)

This doesn't have anything to do with escaping or marking as safe. In fact, it doesn't have anything to do with Django at all.
HTML ignores whitespace, including newlines. If you want to show your code as formatted in the db you should use the <pre> tag.

Related

Django: a custom template tag to convert links inside of a TextField and change the hyperlink text

The scenario is that there are some dynamic texts on some templates, that will contain hyperlinks.
For this, I have a SiteDataKeyValue model, in which the dynamic texts for different parts of the template are inputted. This is the model:
class SiteDataKeyValue(models.Model):
key = models.CharField(
max_length=200, verbose_name="نام متن مورد نظر", unique=True
)
value = models.TextField(verbose_name="متن")
def __str__(self):
return self.key
A solution that I've found already, is Django urlize template tag. As mentioned in the docs, this tag converts texts like https://www.google.com to www.google.com, which is nice but not what I'd like to achieve. I want to be able to change the hyperlink text, so the output would be something like: Click Here!.
I searched for a bit, came across modules like bleach, which is a fine module, but I couldn't find the answer I was looking for (I skimmed through the docs and there was nothing about the hyperlink text).
Also I saw a comment somewhere telling that this could be achieved by writing a custom Django template tag, but although I tried to do this regarding the custom template filters docs, I didn't have a clue to how to achieve this.
I'm not asking for the code, although it would be really appreciated if you provide instructions for writing this custom template tag, or better, if you could point me to something like this that is already out there.
First of all you can extend urlize tag like the answer in this
or you can change the main code which you can find it in django.utils.html and override its url variable to change it.
But I think the best method is extending the urlize tag
like this:
{% text | urlize | change_a_text_filter:{{ dome_new_a_text }} %}
then you can scrape the text and use regex to find >sample-text</a> then you can change it to the argument that defines in your tag
from django import template
register = template.Library()
#register.simple_tag
def change_a_text_filter(format_string, arg):
# find the url that made in urlize with regex
# change it with arg
# return the result
I was on a completely wrong road to solve this problem. I was trying to urlize a link from TextField, but didn't consider the fact that I only needed to implement html code as Visit link.com! in the TextField, and then use safe template tag to render html directly as below:
{{ text.value|safe }}
So in this solution, there is no need to urlize, and of course there is no need to extend this tag neither.
NOTE: As commented by #rahimz (link to comment) I understand that there are safety concerns regarding safe tag, So I should emphasize that only me and a company-trusted admin will have access to admin panel and there is no worries that this admin will send malicious code through this TextField.

New Line on Django admin Text Field

I am trying to create a blog o django where the admin posts blogs from the admin site.
I have given a TextField for the content and now want to give a new line.
I have tried using \n but it doesn't help. The output on the main html page is still the same with \n printing in it. I have also tried the tag and allowed tags=True in my models file. Still the same. All the tags are coming as it is on the html page.
My Django admin form submitted:
The result displayed in my public template:
You should use the template filter linebreaks, that will convert the reals \n (that means the newline in the textarea, not the ones you typed using \ then n) into <br />:
{{ post.content|linebreaks }}
Alternatively, you can use linebreaksbr if you don't want to have the surrounding <p> block of course.
After searching the internet and trying different Django Template Filters, I came across one specific filter, SAFE.
For me, LINEBREAKS filter didn't work, as provided by #Maxime above, but safe did.
Use it like this in your html template file.
{{post.content|safe}}
To have a better understanding of SAFE filter, i suggest reading the documentation.
{{post.content|linebreaks}}
This will make the line in the textbox appear as it is without using \n or \.
{{post.content|linebreaksbr}}
Besides the newline function in your CSS Declaration will work too.

Add a newline after each closing html tag in web2py

Original
I want to parse a string of html code and add newlines after closing tags + after the initial form tag. Here's the code so far. It's giving me an error in the "re.sub" line. I don't understand why the regex fails.
def user():
tags = "<form><label for=\"email_field\">Email:</label><input type=\"email\" name=\"email_field\"/><label for=\"password_field\">Password:</label><input type=\"password\" name=\"password_field\"/><input type=\"submit\" value=\"Login\"/></form>"
result = re.sub("(</.*?>)", "\1\n", tags)
return dict(form_code=result)
PS. I have a feeling this might not be the best way... but I still want to learn how to do this.
EDIT
I was missing "import re" from my default.py. Thanks ruakh for this.
import re
Now my page source code shows up like this (inspected in client browser). The actual page shows the form code as text, not as UI elements.
<form><label for="email_field">Email:</label>
<input type="email" name="email_field"/><label
for="password_field">Password:</label>
<input type="password" name="password_field"/><input
type="submit" value="Login"/></form>
EDIT 2
The form code is rendered as UI elements after adding XML() helper into default.py. Thanks Anthony for helping. Corrected line below:
return dict(form_code=XML(result))
FINAL EDIT
Fixing the regex I figured myself. This is not optimal solution but at least it works. The final code:
import re
def user():
tags = "<form><label for=\"email_field\">Email:</label><input type=\"email\" name=\"email_field\"/><label for=\"password_field\">Password:</label><input type=\"password\" name=\"password_field\"/><input type=\"submit\" value=\"Login\"/></form>"
tags = re.sub(r"(<form>)", r"<form>\n ", tags)
tags = re.sub(r"(</.*?>)", r"\1\n ", tags)
tags = re.sub(r"(/>)", r"/>\n ", tags)
tags = re.sub(r"( </form>)", r"</form>\n", tags)
return dict(form_code=XML(tags))
The only issue I see is that you need to change "\1\n" to r"\1\n" (using the "raw" string notation); otherwise \1 is interpreted as an octal escape (meaning the character U+0001). But that shouldn't give you an error, per se. What error-message are you getting?
By default, web2py escapes all text inserted in the view for security reasons. To avoid that, simply use the XML() helper, either in the controller:
return dict(form_code=XML(result))
or in the view:
{{=XML(form_code)}}
Don't do this unless the code is coming from a trusted source -- otherwise it could contain malicious Javascript.

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.

Why won't Django auto-escape my <script> tags?

My Django app has a Person table, which contains the following text in a field named details:
<script>alert('Hello');</script>
When I call PersonForm.details in my template, the page renders the script accordingly (a.k.a., an alert with the word "Hello" is displayed). I'm confused by this behavior because I always thought Django 1.0 autoescaped template content by default.
Any idea what may be going on here?
UPDATE: Here's the snippet from my template. Nothing terribly sexy:
{{ person_form.details }}
UPDATE 2: I have tried escape, force-escape, and escapejs. None of these work.
You need to mark the values as | safe I think (I'm guessing that you're filling in the value from the database here(?)):
{{ value|safe }}
Could you post a sample of the template? Might make it easier to see what's wrong
[Edit] ..or are you saying that you want it to escape the values (make them safe)? Have you tried manually escaping the field:
{{ value|escape }}
[Edit2] Maybe escapejs from the Django Project docs is relevent:
escapejs
New in Django 1.0.
Escapes characters for use in JavaScript strings. This does not make the string safe for use in HTML, but does protect you from syntax errors when using templates to generate JavaScript/JSON.
[Edit3] What about force_escape:
{{ value|force_escape }}
...and I know it's an obvious one, but you're absolutely certain you've not got any caching going on in your browser? I've tripped over that one a few times myself ;-)
Found the problem. The JSON string I'm using to render data to some Ext widgets is the culprit. Big thanks to Jon Cage. Answer accepted despite the problem being caused by another source.