Skip to main content

Command Palette

Search for a command to run...

Build a simple YouTube video downloader using Python and Django

Updated
3 min read
Build a simple YouTube video downloader using Python and Django
W

Full Stack | building, breaking, tricking my brain

This tutorial will show you how to create a simple application that downloads YouTube videos. We can do this in few lines of Python code, basic HTML and Django.

What we need?

pytube: We will be using pytube library. 'pytube' (https://pytube.io/en/latest/) is a lightweight, Pythonic, dependency-free, library (and command-line utility) for downloading YouTube Videos.

Django: Django (https://www.djangoproject.com/) is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source.

Project SetUp:

To install the libraries in separate folder, create a virtual environment.

$ py -3 -m venv env

Now activate the environment:

$ .\env\Scripts\activate

(This project is done on Windows machine)

We can now install the libraries in the env.

$ pip install django
$ pip install pytube

We can now start creating our project.

1/ It is time to create our project. To create the project run the following command. It will create a project named 'YTVdownloader'

$ django-admin startproject YTVdownloader
$ cd YTVdownloader

2/ Let's create the video downloader application in our project.

$ python manage.py startapp YTVapp

We need to add our app in INSTALLED_APPS list in the settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'YTVapp',  # our app
]

3/ Go to views.py. Create a function that receives the video link and download video from that link. We need to import YouTube function from pytube.

from django.shortcuts import render
from pytube import YouTube

def index(request):

    try:

        # check request.method is post or not
        if request.method == 'POST':
            try:
                # get link from the html form
                link = request.POST['link']
                video = YouTube(link)

                # set video resolution
                stream = video.streams.get_lowest_resolution()

                # download the video 
                stream.download()

                # render HTML page
                return render(request, 'index.html', {'msg':'Video downloaded'})
            except:
                return render(request, 'index.html', {'msg':'Video not downloaded'})
        return render(request, 'index.html', {'msg':''})
    except:
        return render(request, "index.html", {"msg":"Sorry something went wrong!"})

4/ To define how to display it to the users, we will need a HTML file.

First, create a 'templates' folder inside 'YTVapp'.

Inside the templates folder, we will create 'index.html' file where user can enter the url from YouTube to download the video. To do this we will use Django's POST method using csrf token for security.

<!DOCTYPE html>
<html>

<head>
    <style>
        .container {
            text-align: center;
        }

        .form {
            width: 100%;
        }
    </style>
</head>

<body>

    <div class="container">
        <h1>Youtube video downloader</h1>

        <p>{{msg}}</p>

        <form action="" method="post" class="form">
            {% csrf_token %}

            <label for="link">Enter URL: </label>
            <input type="text" id="link" name="link"><br><br>
            <input type="submit" value="Download">
        </form>
    </div>

</body>

</html>

5/ Now we will define the path or map urls to views inside the urls.py

from django.contrib import admin
from django.urls import path
from YTVapp import views

urlpatterns = [
    path('', views.index, name='index'),
    path('admin/', admin.site.urls),

]

6/ We are all set to run our project: In the command line type:

$ python manage.py runserver

Go to http://localhost:8000/youtube to check our YouTube video downloader.

When you click on Download button a video will be downloaded in your Django project’s directory.

image.png

Code in GitHub

D

Well shall I look at the project or how to download youtube videos ?

Joke apart.. there is a lot to learn from your guide that uses the Django framework. Also, I have a question. Will it be able to download the videos those are restricted by default to be able to download?

I see that this project just uses the stream.download() to download the stream file without going for extra check or verification.

1
W
Wulfi4y ago

Actually I would like to thank you for pointing out, I haven't thought of going further but there are a lot more feature we can try out with this 'very serious, lightweight, dependency-free Python library' mentioned here (https://pypi.org/project/pytube/).

Well for someone who is starting with Django, Python, pytube, this may be an interesting and a fun beginner project if not there's a next step too. If you say 'how to download youtube videos?', we may get many options to choose from the websites or applications available out there but it is good if can create our own. Moreover, this library does not use any third-party dependencies and aims to be highly reliable.

I won't be able to say we can download the restricted videos as it is restricted but I'm sure some of them can't be downloaded we can check it by checking the properties of objects.

Similarly, any checks can be done by creating the objects and getting its properties.

Links:

  1. https://www.studytonight.com/post/pytube-to-download-youtube-videos-with-python

  2. https://pypi.org/project/pytube/

D

Wulfi Thanks for a detailed answer. Yes, true that this is a beginner project and can be made giant if one is really interested to go in depth.