I defined my custom Django filter youtube_embed_url in templatetags/custom_filters.py. It takes an Youtube url and returns the string which is embed code for the video. The code for templatetags/custom_filters.py is below:
from django import template
from django.conf import settings
register = template.Library()
import re
#register.filter(name='youtube_embed_url')
# converts youtube URL into embed HTML
# value is url
def youtube_embed_url(value):
match = re.search(r'^(http|https)\:\/\/www\.youtube\.com\/watch\?v\=(\w*)(\&(.*))?$', value)
if match:
embed_url = 'http://www.youtube.com/embed/%s' %(match.group(2))
res = "<iframe width=\"560\" height=\"315\" src=\"%s\" frameborder=\"0\" allowfullscreen></iframe>" %(embed_url)
return res
return ''
youtube_embed_url.is_safe = True
Then I use this filter in link_page.html page. Here is the relevant portion of link_page.html:
<div>
{{ link.url|youtube_embed_url }}
</div>
However, when I view the link page in browser I see the HTML code as the string:
Any idea how to make the result of youtube_embed_url method to be interpreted as the HTML code, not a string? Thanks in advance, guys!
Good ol' safe filter.
{{ link.url|youtube_embed_url|safe }}
You can also use django-embed-video.
Usage is quite similar:
{% load embed_video_tags %}
{{ link.url|embed:'560x315' }}
Related
Using Django, I am sending an html email that contains links but I can't get the links to work. I've tried using {{request.get_full_path}} in my template, as well as request.build_absolute_uri() in my view. Any help would be great!
In my site, the correct url is given in the template like this, with url="/review_and_export/":
BibTex
Currently, this is my email code:
views.py
# for links in html email??
full_url = request.build_absolute_uri()
full_url = full_url.split("/software/", 1)[0] #this produces just the domain, EDIT: i was missing a slash...still having issues
html_content = render_to_string(email_it, {'full_url' : full_url,....}, context_instance=RequestContext(request))
email_it.html
{% for publication in value %}
{% include "software/display_citations.html" with publication=publication url=full_url%}
{% endfor %}
display_citations.html
# I use full_url and request.get_full_path because get_full_path doesn't return the domain
BibTex
I figured it out by further manipulating the url in my views and then concatenating that result with the argument in my template. Thank you for your help!
i want to put some data from the database into the admin index page, so i am trying to add some code to the index.html, but the commands such as Model_name.object.get() don't seem to work there
<ul>{% trans 'Last Update at ' %}
{% for entryupdate in Updatetime.objects.all %}
{{ entryupdate.updatetime }}
{% endfor %}
</ul>
so what shall i use instead? The problem is that there is no variable associated with the object i need. If that would have been any other page i could have added the variable in the views.py, but that's not the case. Thank you!
Those sorts of functions don't work in any template.
You should use a custom template tag to query the data and return it.
Thank to the tip of Daniel i created that tag:
import datetime
from django import template
from Myapp.models import Updatetime
register = template.Library()
def update_time():
ss = Updatetime.objects.get(pk=1)
str11 = ss.updatetime.strftime("%d-%m-%Y %H:%M:%S")
return str11
register.simple_tag(update_time)
I'm using Django 1.3 and I have a simple_tag that I need to return some un-escaped HTML and no matter what I do it's still escaping my & to & and my | to %7C.
from django import template
from django.template import loader, Context
from django.utils.safestring import mark_safe
register = template.Library()
#register.simple_tag()
def show_stuff(arg1=None, arg2=None, arg3='someconstant'):
# Do some stuff
if someconstant == 'somevalue':
template_name = 'template1.html'
else:
template_name = 'template2.html'
template = loader.get_template(template_name)
html = template.render(Context( {'myvar': myvar,} ))
html = mark_safe(html)
print type(html)
return html
The print statement reveals
<class 'django.utils.safestring.SafeUnicode'>
which from my understanding isn't supposed to be escaped. I'm calling the tag in my template like so:
{% show_stuff 'arg1' 'arg2' 'arg3' %}
Help would be greatly appreciated.
Update: Tried the following from comments below. Didn't return an error, but still escapes the HTML:
...
template = loader.get_template(template_name)
html = template.render(Context( {'myvar': myvar,} ))
html = mark_safe(html)
print type(html)
return html
show_stuff().is_safe=True
Also tried wrapping the contents of template1.html and template2.html in
{% autoescape off %}
template html contents with & and |
{% endautoescape %}
and wrapping the templatetag call itself with autoescape tags. No success.
Old thread but I ran into the same issue recently. I got it working python 3.6. Assign the value from simple tag to a variable txt and output the txt using template tags "{{" and add safe filter to txt.
{% get_contentvalue user "htmlabout" as txt %}
{{txt|safe}}
In discussion with the author of the question we found that the characters were not actually escaped. Scoopseven (the author) viewed the source html with the option "Show Selection Source" of a context menu in Firefox. In this case escaped characters are shown.
I have a puzzle, my haystack+whoosh works just fine:) I can search through f.e. name of the content. BUT I want to add "taggit" to my core-model and search through tags then I have NO results:// and I don't know why. More precisely I know that content name "X" has a tag "foo" and when I make search through "foo" I have no result:/
Taggit is a simple tag module for django. Here is the part of my search_indexes.py file:
import datetime
from haystack.indexes import *
from haystack import site
from models import Skill
class SkillIndex(SearchIndex):
text = CharField(document = True, use_template = True)
tags = CharField(model_attr='tags')
site.register(Skill, SkillIndex)
Best regards,
nykon
PS My target is to make live-search like google by use of tags. Does someone has a good idea?
You can add the tags to the data template,
For example:
{{ object.name }}
{% for tag in object.tags.all %}{{ tag.name }} {% endfor %}
Not sure that this is the best solution, but it works.
I am using couchdb-python with Django. I am looking for a way to display an image (which is stored in the database as an attachment to a document) in a template. Oddly, I cannot find any example online of how to do this.
Currently, in the views.py I have something like this:
def displaypage(request,id):
docs = SERVER['docs']
try:
doc = docs[id]
except ResourceNotFound:
raise Http404
...
attachments = doc['_attachments']['someimage.jpg']
...
text_marked_down = markdown.markdown(doc['text'])
return render_to_response('couch_docs/display.html',{'row':doc,'attachments':attachments,'doctext':text_marked_down,...},context_instance=RequestContext(request))
Then, in the template display.html:
{% extends 'site_base.html' %}
{% block wrapper %}
{{ attachments }}
<div>{{ doctext|safe }}</div>
{{ endblock }}
I am seeing the text just fine, but for the image I only see the following:
{u'stub':True, u'length':27018,u'revpos':19,u'content_type': u'image/jpeg'}
So, clearly I am not passing the actual image, or not displaying it correctly anyway. Oddly, I cannot find an example online anywhere of how to actually do this. Can anyone point me to one, or provide it here?
You are using the template engine to render an HTML document. That document will be interpreted by the web browser just like any other HTML document.
Think about how an HTML page contains an image. The image is never inline within the HTML document itself. The HTML page contains a reference to instruct the browser to separately load the image and display it in place.
<img src="/path/to/image" />
So, likewise, you will need to:
create a separate view that will only return the binary data of the image. Set the mime type appropriately. See http://effbot.org/zone/django-pil.htm for some ideas how to return an image, but in your case set the contents of the response to be your image content.
add an <img ...> tag to your template that calls the new view you created.
once you drill down your db, you might want to consider building the url of each documents attachment as follows:
def function():
couch = couchdb.Server() #connect to server
db = couch['img'] #connect to database which contains docs with img attachments
doc_id = [] #create list of id's
http_docid = [] #create list to populate href for picture path
for i in db: #for each id in the db
doc_id.append(i) #add to the carid list
doc = db[i] #get the document id
for key in (doc['_attachments']): #for the key in the doc '_attacments' payload
print key #just to confirm
href_docid.append(('http://yourdbDomain/dbname/'+i+'/'+key)) #create a uri and append to a list
return href_docid
And below im using Jinja2's templating:
{% for img in function() %}
<img class="some-class" src="{{ img }}">
{% endfor %}
Hope this proves usefull!