Embedding Videos Into Django Project

Have you ever tried to embed a video into your Django website so find that it wouldn’t work?

Well, I have.

Let’s go over the solution I found to this problem.

The problem

I’ve been making an app for some other people that I mentor. I decided it would be much easier and more beneficial to my mentees if I answered their questions in video instead of writing. Speeds things along and I can do more volume while conveying my non-verbal communication.

I expected to just hold a Vimeo URL in the database and plug it into a set embed code in my template.

Long story short: that didn’t work. So I went searching for a new answer.

Answer: django-embed-video

I found the solution in a lovely plugin package, django-embed-video.

Install the package

pip install django-embed-video

Change settings.py

INSTALLED_APPS = (
    ...
    'embed_video',
)

Add the field to your model

# app_name/models.py
from django.db import models
from embed_video.fields import EmbedVideoField

class ModelName(models.Model):
    video = EmbedVideoField(blank=True) # an empty field is fine for me

Load the tags at the top of your template

{# for me, this was app_name/model_name_detail.html #}
{% load embed_video_tags %}

Call the video in the template

{# still app_name/model_name_detail.html #}
{# the string at the end is the size of the video #}
{# options: tiny, small, medium, large, huge #}
{% video model_name.video 'medium' %}

Other features

You can also add your new model field to the Django admin and customize the video backends.

Plus, you can embed audio from SoundCloud if video isn’t your thing.

My favorite part about it is that it will auto-detect which backend to use based on the link. Super simple in case I end up switching from Vimeo to YouTube.

Alternative Solutions?

That’s it! If you’ve ever solved this problem, tell us a story in the comments below. I’d love to hear what other solutions are out there.

Likewise, if you’ve ever written your own custom backend, share the tale!

1 Comment

Leave a Reply