django-embed-video’s documentation¶
Django app for easy embeding YouTube and Vimeo videos and music from SoundCloud.
Repository is located on GitHub: https://github.com/yetty/django-embed-video
Installation & Setup¶
Installation¶
The simpliest way is to use pip to install package:
pip install django-embed-video
If you want latest version, you may use Git. It is fresh, but unstable.
pip install git+https://github.com/yetty/django-embed-video.git
Setup¶
Add embed_video to INSTALLED_APPS in your Django settings.
INSTALLED_APPS = (
...
'embed_video',
)
To detect HTTP/S you must use request context processor:
TEMPLATE_CONTEXT_PROCESSORS = (
...
'django.core.context_processors.request',
)
Examples¶
Template examples¶
First you have to load the embed_video_tags template tags in your template:
{% load embed_video_tags %}
Embedding of video:
{# you can just embed #}
{% video item.video 'small' %}
{# or use variables (with embedding, too) #}
{% video item.video as my_video %}
URL: {{ my_video.url }}
Thumbnail: {{ my_video.thumbnail }}
Backend: {{ my_video.backend }}
{% video my_video 'small' %}
{% endvideo %}
Default sizes are tiny (420x315), small (480x360), medium (640x480), large (960x720) and huge (1280x960). You can set your own size:
{% video my_video '800x600' %}
And use relative percentual size:
{% video my_video '100% x 50%' %}
Tip
We recommend to use sorl-thumbnail to change thumbnail size.
Tip
To speed up your pages, consider template fragment caching.
Tip
You can overwrite default template of embed code located in templates/embed_video/embed_code.html or set own file for custom backend (template_name).
Model examples¶
Using the EmbedVideoField provides you validation of URLs.
from django.db import models
from embed_video.fields import EmbedVideoField
class Item(models.Model):
video = EmbedVideoField() # same like models.URLField()
Admin mixin examples¶
Use AdminVideoMixin in admin.py.
from django.contrib import admin
from embed_video.admin import AdminVideoMixin
from .models import MyModel
class MyModelAdmin(AdminVideoMixin, admin.ModelAdmin):
pass
admin.site.register(MyModel, MyModelAdmin)
Custom backends¶
If you have specific needs and default backends don’t suits you, you can write your custom backend.
my_project/my_app/backends.py:
from embed_video.backends import VideoBackend
class CustomBackend(VideoBackend):
re_detect = re.compile(r'http://myvideo\.com/[0-9]+')
re_code = re.compile(r'http://myvideo\.com/(?P<code>[0-9]+)')
allow_https = False
pattern_url = '{protocol}://play.myvideo.com/c/{code}/'
pattern_thumbnail_url = '{protocol}://thumb.myvideo.com/c/{code}/'
template_name = 'embed_video/custombackend_embed_code.html' # added in v0.9
You can also overwrite VideoBackend methods, if using regular expressions isn’t well enough.
my_project/my_project/settings.py:
EMBED_VIDEO_BACKENDS = (
'embed_video.backends.YoutubeBackend',
'embed_video.backends.VimeoBackend',
'embed_video.backends.SoundCloudBackend',
'my_app.backends.CustomBackend',
)
Low level API examples¶
You can get instance of VideoBackend in your python code thanks to detect_backend():
from embed_video.backends import detect_backend
my_video = detect_backend('http://www.youtube.com/watch?v=H4tAOexHdR4')
Example project¶
For easy start with using django-embed-video, you can take a look at example project. It is located in example_project directory in root of repositary.
Running example project¶
Install Django and PyYAML:
pip install Django pip install pyyaml
Create database:
python manage.py syncdb --noinput
Run testing server:
python manage.py runserver
Take a look at http://localhost:8000 . You can log in to administration with username admin and password admin.
Testing HTTPS¶
To test HTTPS on development server, follow this instructions.
Development¶
Contributing¶
I will be really pleased if you will provide patch to this Django app. Feel free to change whatever, but keep PEP8 rules and Zen.
It is a good habit to cover your patches with tests.
Repository is hosted on Github: https://github.com/yetty/django-embed-video
Testing¶
Requirements¶
The library needs Django and requests and nose, mock, south and textfixtures libraries to run tests.
pip install Django
pip install requests
pip install nose
pip install mock
pip install south
pip install textfixtures
Running tests¶
Run tests with this command:
nosetests
Be sure to run it before each commit and fix broken tests.
Run tests with coverage:
pip install coverage
nosetests --with-coverage --cover-package=embed_video
Changelog¶
Release 0.10 (dev)¶
Nothing yet.
Release 0.9 (Apr. 4, 2014)¶
Release 0.8 (Feb. 22, 2014)¶
- Add EMBED_VIDEO_TIMEOUT to settings.
- Fix renderering template tag if no url is provided (#18)
- If EMBED_VIDEO_TIMEOUT timeout is reached in templates, no exception is raised, error is just logged.
- Fix default size in template tag. (See more...)
Release 0.7 (Dec. 21, 2013)¶
- Support for sites running on HTTPS
- embed filter is deprecated and replaced by video filter.
- caching for whole backends was removed and replaced by caching properties
- minor improvements on example project (fixtures, urls)
Release 0.6 (Oct. 04, 2013)¶
- Ability to overwrite embed code of backend
- Caching backends properties
- PyPy compatibility
- Admin video mixin and video widget
Release 0.5 (Sep. 03, 2013)¶
- Added Vimeo thumbnails support
- Added caching of results
- Added example project
- Fixed template tag embed
- Fixed raising UnknownIdException in YouTube detecting.
Release 0.4 (Aug. 22, 2013)¶
- Documentation was rewrited and moved to http://django-embed-video.rtfd.org/ .
- Custom backends (http://django-embed-video.rtfd.org/en/latest/examples.html#custom-backends).
- Improved YouTube and Vimeo regex.
- Support for Python 3.
- Renamed base to backends.
Release 0.3 (Aug. 20, 2013)¶
Security fix: faked urls are treated as invalid. See this page for more details.
Fixes:
- allow of empty video field.
- requirements in setup.py
Added simplier way to embed video in one-line template tag:
{{ 'http://www.youtube.com/watch?v=guXyvo2FfLs'|embed:'large' }}
backend variable in video template tag.
Usage:
{% video item.video as my_video %} Backend: {{ my_video.backend }} {% endvideo %}
Release 0.2 (June 25, 2013)¶
- Support of SoundCloud
Release 0.1 (June 1, 2013)¶
- Initial release
TODOs list¶
Todo
Django 1.6 provides better parent for this widget - django.forms.URLInput.
(The original entry is located in /var/build/user_builds/django-embed-video/checkouts/v0.9/embed_video/admin.py:docstring of embed_video.admin.AdminVideoWidget, line 5.)
API¶
API reference¶
Admin¶
- class embed_video.admin.AdminVideoMixin[source]¶
Mixin using AdminVideoWidget for fields with EmbedVideoField.
Usage:
from django.contrib import admin from embed_video.admin import AdminVideoMixin from .models import MyModel class MyModelAdmin(AdminVideoMixin, admin.ModelAdmin): pass admin.site.register(MyModel, MyModelAdmin)
- class embed_video.admin.AdminVideoWidget(attrs=None)[source]¶
Widget for video input in administration. If empty it works just like django.forms.TextInput. Otherwise it renders embedded video together with input field.
Todo
Django 1.6 provides better parent for this widget - django.forms.URLInput.
Backends¶
- exception embed_video.backends.EmbedVideoException[source]¶
Parental class for all embed_video exceptions
- class embed_video.backends.SoundCloudBackend(url, is_secure=False)[source]¶
Backend for SoundCloud URLs.
- exception embed_video.backends.UnknownBackendException[source]¶
Exception thrown if video backend is not recognized.
- exception embed_video.backends.UnknownIdException[source]¶
Exception thrown if backend is detected, but video ID cannot be parsed.
- class embed_video.backends.VideoBackend(url, is_secure=False)[source]¶
Base class used as parental class for backends.
class MyBackend(VideoBackend): ...
- allow_https = True¶
Sets if HTTPS version allowed for specific backend.
- get_embed_code(width, height)[source]¶
Returns embed code rendered from template template_name.
- get_thumbnail_url()[source]¶
Returns thumbnail URL folded from pattern_thumbnail_url and parsed code.
- get_url()[source]¶
Returns URL folded from pattern_url and parsed code.
- classmethod is_valid(url)[source]¶
Class method to control if passed url is valid for current backend. By default it is done by re_detect regex.
- pattern_thumbnail_url = None¶
Pattern in which the code is inserted to get thumbnail url.
Example: http://static.myvideo.com/thumbs/%s
- pattern_url = None¶
Pattern in which the code is inserted.
Example: http://myvideo.com?code=%s
- re_code = None¶
Compiled regex (re.compile()) to search code in URL.
Example: re.compile(r'myvideo\.com/\?code=(?P<code>\w+)')
- re_detect = None¶
Compilede regec (re.compile()) to detect, if input URL is valid for current backend.
Example: re.compile(r'^http://myvideo\.com/.*')
- template_name = 'embed_video/embed_code.html'¶
Name of embed code template used by get_embed_code().
Passed template variables: {{ backend }} (instance of VideoBackend), {{ width }}, {{ height }}
- exception embed_video.backends.VideoDoesntExistException[source]¶
Exception thrown if video doesn’t exist
- embed_video.backends.detect_backend(url)[source]¶
Detect the right backend for given URL.
Goes over backends in settings.EMBED_VIDEO_BACKENDS, calls is_valid() and returns backend instance.
Fields¶
- class embed_video.fields.EmbedVideoField(verbose_name=None, name=None, **kwargs)[source]¶
Model field for embeded video. Descendant of django.db.models.URLField.
- class embed_video.fields.EmbedVideoFormField(max_length=None, min_length=None, *args, **kwargs)[source]¶
Form field for embeded video. Descendant of django.forms.URLField
Settings¶
EMBED_VIDEO_BACKENDS¶
List of backends to use.
Default:
EMBED_VIDEO_BACKENDS = (
'embed_video.backends.YoutubeBackend',
'embed_video.backends.VimeoBackend',
'embed_video.backends.SoundCloudBackend',
)
Template tags¶
You have to load template tag library first.
{% load embed_video_tags %}
Template tag video. It gives access to all VideoBackend variables.
Usage (shortcut):
{% video URL [SIZE] %}
Or as a block:
{% video URL as VAR %} ... {% endvideo %}
Example:
{% video item.video "large" %} {% video item.video "340x200" %} {% video item.video "100% x 300" %} {% video item.video as my_video %} URL: {{ my_video.url }} Thumbnail: {{ my_video.thumbnail }} Backend: {{ my_video.backend }} {% endvideo %}
Direct render of embed video.
Returns instance of VideoBackend. If context is passed to the method and request is secure, than the is_secure mark is set to backend.
A string or VideoBackend instance can be passed to the method.
Predefined sizes:
size width height tiny 420 315 small 480 360 medium 640 480 large 960 720 huge 1280 960 You can also use custom size - in format WIDTHxHEIGHT (eg. 500x400).
Warning
Deprecated since version 0.7: Use VideoNode.embed() instead.
Same like VideoNode.embed() tag but always uses insecure HTTP protocol.
Usage:
{{ URL|embed:SIZE }}
Example:
{{ 'http://www.youtube.com/watch?v=guXyvo2FfLs'|embed:'large' }}
Utils¶
- embed_video.utils.import_by_path(dotted_path, error_prefix='')[source]¶
Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImproperlyConfigured if something goes wrong.
Warning
Deprecated since version Django: 1.6
Function django.utils.module_loading.import_by_path() has been added in Django 1.6.