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/
Related
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 }}
What is best way to replace custom "tag" (for example [IMG]image_name[/IMG]) with image url what exist in model as imagefield? For example:
class ImageResource(models.Model):
name = models.CharField(verbose_name='Name')
img = models.ImageField(verbose_name='Image')
class Post(models.Model):
title = models.CharField(verbose_name='Title')
text = models.TextField(verbose_name='Text')
images = models.ManyToManyField(ImageResource,verbose_name="Images")
DetailView to display template like this:
{{ object.text }}
I will replace all [IMG]name[/IMG] in object.text to html img code who has src = images.url when images.name == name only.
I don't want use wysiwyg editor. I don't know what is best place to do this - on model, view (what function?) or in specific filter?
it depends on your needs, you can use it in the templatetags if you only want to show the images in the template. But, you can also process it at the views. Here is an example templatetags to find the markdown images.
Regex demo
#register.filter
def markdown_find_images(markdown_text):
"""
return list of image urls inside `markdown_text`.
:param `markdown_text` is markdown text to find.
example markdown text:
Hello ![title](/path/to/image.png)
provides for:
jpeg|jpg|png|gif
usage:
{{ field_name|markdown_find_images }}
example:
{{ post.description|markdown_find_images }}
"""
regex = r"[^(\s]+\.(?:jpeg|jpg|png|gif)(?=\))"
return re.findall(regex, markdown_text)
In your case, demo:
#register.filter
def find_images(plain_text):
"""
return list of image urls inside `markdown_text`.
:param `markdown_text` is markdown text to find.
example markdown text:
Hello [img]/path/to/image.png[/img]
provides for:
jpeg|jpg|png|gif
usage:
{{ field_name|find_images }}
example:
{{ post.description|find_images }}
"""
regex = r"\[img\](.+?)\[\/img\]"
return re.findall(regex, plain_text)
Django 1.7. I need to insert the content of text file from the model in django template. It's important that it must be a file not a text field of the model.
Is there a way to do it?
Here is my model:
class Model1(models.Model):
file1 = FilerFileField(null=True, blank=True)
file2 = FilerFileField(null=True, blank=True)
I tried {% include %} tag and it doesn't work.
{% include %} is for including templates (which will be searched in settings.TEMPLATE_DIRS) so no surprise it doesn't work.
Mainly, you'll have to read the files from Python code and pass it to the template's context. Three possible solutions here:
1/ add a method to your model to get your FilerFileField's content
2/ write a custom template filter (or tag) that takes the FilerFileField and returns the file's content
3/ read the FilerFileField's contents in the view and add them to the context
Tag include is not about inserting something from model into your template. Is about inserting content of specified template. You need to write custom template filter which will read your file content and return it into template:
from django import template
register = template.Library()
#register.filter
def print_file_content(f):
try:
return f.read()
except IOError:
return ''
And use it into template like:
<div>{{ object.file1|print_file_content }}</div>
Or you can pass it through template context. Then just read file content into your view and add this content to your template context dictionary.
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.