RkBlog

Hardware, programming and astronomy tutorials and reviews.

Using oEmbed in Django

Replacing links to multimedia websites with nice embedded players, thumbs and other content using django-oembed.

oEmbed is a format, API to present links to multimedia websites like Flick or YouTube in a nice and content rich way. Easy and clean way to replace all links in a blog post or article to embedded players, or thumbs of linked images. You can look at embed.ly for a list of popular websites supporting oEmbed.

Site that supports oEmbed provide URL that handles the API requests, like: http://www.flickr.com/services/oembed/. It also has to provide information about which links are supported, for example: http://www.flickr.com/photos/*. If we have those informations we can use the oEmbed API to get details about a link:

http://www.flickr.com/services/oembed/?url=http://www.flickr.com/photos/91784720@N00/4868367542/in/pool-astrometry/
Which will return:
<oembed>
<version>1.0</version>
<type>photo</type>
<title>LAGOON AND TRIFFID IN H ALPHA</title>
<author_name>Narayan Mukkavilli</author_name>
<author_url>http://www.flickr.com/photos/91784720@N00/</author_url>
<cache_age>3600</cache_age>
<provider_name>Flickr</provider_name>
<provider_url>http://www.flickr.com/</provider_url>
<width>500</width>
<height>325</height>
<url>
http://farm5.static.flickr.com/4096/4868367542_8b1c2f8997.jpg
</url>
</oembed>

In Python we can use python-oembed or django-oembed. The Django application gives us ready to use set of template tags and database full of configs of sites supporting oEmbed.

Django-oembed

To install django-oembed get the sources:
svn checkout http://django-oembed.googlecode.com/svn/trunk/ django-oembed
And install it the standard way:
python setup.py install
In settings.py of your Django project add 'oembed' to INSTALLED_APPS and create tables for the application (syncdb). If the syncdb won't import django-oembed fixtures then copy oembed/fixtures/initial_data.json to project folder and execute:
python manage.py loaddata initial_data.json

The application is installed and ready to use.

In Django templates you can load the oembed tags by: {% load oembed_tags %} and use them on content:
{{ blog.content|oembed:"600x600" }}

or:

{% oembed %}{{ blog.additional_content }}
<p>blablabla</p>
http://www.flickr.com/photos/riklaunim/4859954938/
<p>blaa</p>
{% endoembed %}
The parser used in those tags is bit odd and may not parse link if the content doesn't show a structure of a HTML document (some HTML tags before/after the link needed), When it will work the links will be nicely replaced, for example like this:
oembed
RkBlog

8 August 2010;

Comment article