I'm working on a Django project in Python and using markdown2 to convert some markdown text into HTML but it appears to not be doing it well or I'm missing something in the code.
In my views.py file I'm using a custom function to extract some text from an .md file in markdown format and with the markdown2 module I try pass it on to the HTML template like so:
text = markdown2.markdown(util.get_entry(entry))
But in the HTML, if I inspect the source code what is supposed to render as HTML comes out like this:
<h1>HTML</h1>
Am I missing something in my code? Is the error on the HTML template or in my views.py file?
Thanks in advance!
You probably have rendered the content in the template with:
{{ text }}
Django will by default escape the content, and thus replace < with <, etc.
You can make use of the |safe template filter [Django-doc] to prevent this:
{{ text|safe }}
Related
Hi I need to send data in string format to my jinja templates, and the render them. The only way I found is to format my data as JSON and send it as a string to the renderer. But I don´t know how to use it in the templates, it seems that the tojson filter it´s not for this purpose, because it keeps rendered a string.
to keep it simple I'm doing something similar to:
import json
a = {"a":1,"b":[1,2,3,4]}
response = json.dumps(a)
in template:
{{ response }}
{{ response|tojson }}
both give a string response, not a dict or an object that I can use to render based on the values
You can import json to use it's load function to load it into jinja.
from json import loads
environment = jinja2.Environment(whatever)
environment.filters['load'] = loads
{{ response|load }}
Reference:
Import a Python module into a Jinja template?
I have a variable
text = "replace some word"
in a view. I want to replace 'some' to bold. Like this:
"replace **some** word"
How to handle that variable in django template?
Obviously, the ** do not make a bold string in a template and you will have a much harder time trying to replace these markers with appropriate opening and closing tags in the template, e.g via a custom filter. However, you can make it bold in the view by applying the necessary HTML there and marking it safe:
# views.py
from django.utils.safestring import mark_safe
# in your view
# ...
text = "replace some word"
# add the appropriate html tags
text = text.replace('some', '<strong>some</strong>')
# now you have to mark it as safe so the tags will be rendered as tags
text = mark_safe(text)
# ...
return render(reqest, template, {.., 'text': text, ...})
Now you can just use it like a normal variable in the template via {{ text }}
You can create custom template tags to render these type of things. You have to write some extra lines of code. But once you do, it's reusable and less tedious to use replace function every time.
Create a custom tag/filter file called mytags.py, your app layout might look like this:
myapp/
__init__.py
models.py
templatetags/
__init__.py
mytags.py
views.py
Write in mytags.py:
from django import template
register = template.Library()
def bold(text):
return text.replace('**','<strong>',1).replace('**','</strong>',1)
register.filter('bold', bold)
In your template, first load the custom tag file:
{% load mytags %}
Apply this custom tag to the text:
{{ text|bold }}
For reference: https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/
I am using django-summernote editor for creating posts with text and images which are saved in a character field as HTML tags.
I want to add a read-more functionality where a limited sized preview is shown for all the posts. An idea could be to truncate the character field, but it may lead to truncation of HTML image tags if they happen to be positioned between the boundary.
How to get around this?
Django has two template filters you can use to make sure your HTML doesn't get malformed: truncatechars_html and truncatewords_html
Template filters are just functions, so you can import them anywhere you need in your Python code and assign the result to a variable you can use elsewhere, etc.
Example:
from django.template.defaultfilters import truncatechars_html
html = """<p>Look, I’m some HTML. You can truncate me
with Django template filters</p>"""
truncated_value = truncatechars_html(html, 30)
I'm late to this party but this post came up in search results. I just got a working solution to this myself with a custom template filter. This allows you to drop in the break on a case by case basis like WordPress. Here is what I did (with help from this post and the Django docs):
Sample post submitted in a textfield:
<p>Here is some sample text</p>
<!--more-->
<img src="cool_photo.jpg" />
in templatetags/read_more.py
from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
#register.filter(name='read_more')
#stringfilter
def read_more(value):
pattern = "<!--more-->"
return value.split(pattern, 1)[0]
in the template that's rendering the truncated version:
{% load read_more %}
{{ object.body|read_more|safe }}
Since the split pattern is an html comment there's no need to cut it from the main post body template:
{{ object.body|safe }}
i like to use the url template tag in my model's content.
example:
models content:
Car.description = 'this is a link to our main page: home'
in template.html:
<div>{{ Car.description }}</div>
result
<div>this is a link to our main page: home
is it possible, or do i have to write my own template tag?
thanks in advance
Roman
Assuming you have this:
car.description = 'this is a link to our main page: home'
You can do:
from django.template import Context, Template
from django.core.urlresolvers import reverse
class Car(models.Model):
def description_with_url(self):
return Template(self.description).render({'url': reverse('home')})
or use the same logic in custom template tag instead of method..
I can't figure out why you would need to do that. Assuming that I fully-understood your question, you are attempting to store something within a model's field that then behaves "dynamically" when rendered.
A model field's content that stores a URL should contain a URL and only a URL by utilizing the URLField.
Else, if you're dynamically building the URL from somewhere else, simply use template markup, i.e. the url template tag as it is meant to be used; it can also take parameters depending on the specific URL pattern. I.e. the url tag is meant to be used in the template's context.
Let me know if you update the question to describe what you are trying to achieve. But storing "behaviour" at data level is something to simply stay away from.
I want to create a reusable template (almost like a UserControl from the .NET world) that I can apply in multiple places, something like:
{% for thing in things %}
{% render_thing thing %}
{% endfor %}
Where render_thing is my custom inclusion tag. My Python code reads as follows:
def get_full_path(relative_path):
return os.path.join(os.path.dirname(__file__), relative_path)
def render_thing(thing):
return {'thing':thing }
register = template.create_template_register()
register.inclusion_tag(get_full_path('thing.html'))(render_thing)
Where thing.html is my little template. However, when I run this I get the error:
TemplateSyntaxError: Invalid block tag: 'render_thing'
What am I missing?
If you are using Django 1.2 templates, you will need to supply a Python module-style reference to your custom tag code rather than a file path.
There's a full description of the problem and the solution on my blog.
EDIT:
Sorry to be so high-level on you. Here's a more step-by-step explanation:
Put your custom tag code in a file, say my_custom_tags.py for the sake of example.
take the .py file that your custom tag code lives in and put it in a subdirectory of your main AppEngine project directory, say customtags for the sake of an example.
in that new subdirectory, create an empty file that has the name __init__.py
in your AppEngine application's main .py file, add this code:
from google.appengine.ext.webapp import template
template.register_template_library('customtags.my_custom_tags')
All of the custom tags defined in your custom tag library should now be available in your template files with no additional work.
load template tag
{% load my_template_library %}
see manual
http://docs.djangoproject.com/en/dev/howto/custom-template-tags/
http://www.mechanicalgirl.com/view/custom-template-tags-in-django/
http://www.protocolostomy.com/2009/08/05/practial-django-projects-custom-template-tags-and-updates-on-linuxlaboratory/
You need to load the templatetag library within each template that uses it.
{% load my_template_library %}