DEV Community

Cover image for Youtube Video Downloader using Python Django

Posted on • Updated on

Youtube Video Downloader using Python Django

Last week, I found this cool python module named pytube which seems interesting to me. For those of you who don't know, pytube module is built for downloading youtube videos for free. After knowing its fundamentals and writing a simple python script, I try to make a Django app out of it. Here's how it is done.

1. Install the Requirements

First, let's install the tools we're going to use in this app:

pip install django
pip install pytube
Enter fullscreen mode Exit fullscreen mode

2. Set-up the Environment

We need to make a project first. After making a directory for it, in our terminal again, run:

# django-admin startproject <project name> .
django-admin startproject base .
# python3 startapp <app name>
python3 startapp app
Enter fullscreen mode Exit fullscreen mode

Now let's configure our Django app in our Django project by listing our app's name in base/ so the project now can access the app:

# base/
    ..... ,
Enter fullscreen mode Exit fullscreen mode

Next, create a inside app. To connect it in our base/

# base/
from django.urls import path,include

urlpatterns = [
    ..... ,
    path('', include('app.urls')),
Enter fullscreen mode Exit fullscreen mode

3. Create Views

Let's start our code by making the main heart of our app, the views. On our app/, add the imports:

# base/
from django.views.generic import View
from pytube import Youtube
from django.shortcuts import render,redirect
Enter fullscreen mode Exit fullscreen mode

And now write the main code. Let's make a class for it that takes a url but no errors if you didn't give any and returns a page:

class home(View):
    def __init__(self,url=None):
        self.url = url
        def get(self,request):
        return render(request,'app/home.html')    
Enter fullscreen mode Exit fullscreen mode

Next step, add a new function in it for fetching the video and for downloading it:

class home(View):

    def post(self,request):
        # for fetching the video
        if request.POST.get('fetch-vid'):
            self.url = request.POST.get('given_url')
            video = YouTube(self.url)
            vidTitle,vidThumbnail = video.title,video.thumbnail_url
            qual,stream = [],[]
            for vid in video.streams.filter(progressive=True):
            context = {'vidTitle':vidTitle,'vidThumbnail':vidThumbnail,
            return render(request,'app/home.html',context)

        # for downloading the video
        elif request.POST.get('download-vid'):
            self.url = request.POST.get('given_url')
            video = YouTube(self.url)
            stream = [x for x in video.streams.filter(progressive=True)]
            video_qual = video.streams[int(request.POST.get('download-vid')) - 1]'../../Downloads')
            return redirect('home')

        return render(request,'app/home.html')

Enter fullscreen mode Exit fullscreen mode

So, Are should views looks like this:

Image description

4. Create Template

As we see above, we configure a home.html file. So now where, going to create it. Make a directory first inside our app directory named templates and another one inside it, named after our app which is app where we store our 'home.html' file.

Image description

<!DOCTYPE html>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>YT Saver</title>
<body style="align-items: center;text-align: center;height: fit-content;border: 3px solid green;">
    <h2>YT SAVER</h2>
    <b><p style="color: coral;">Save your favorite youtube videos for free!!</p></b>
    <form method="post" action="">
        {% csrf_token %}
        <!-- for fetching the video -->
        <input type="text" name="given_url" value="{{url}}" placeholder="enter url..">
        <button type="submit" name="fetch-vid" value="fetch-vid">Proceed</button>

            <img src="{{vidThumbnail}}"/>

        <!-- for downloading the video -->
        {% for x in stream %}
            {{x.resolution}} <button type="submit" name="download-vid" value="{{forloop.counter}}">Download</button>|
        {% endfor %}
Enter fullscreen mode Exit fullscreen mode

5. Create Urls

Since we already set up our base/ above, now we create our app/

from django.urls import path
from . import views

urlpatterns = [
Enter fullscreen mode Exit fullscreen mode

6. Test the app

And now, we can finally test our app. Let's run the app, open the terminal, and type:

python runserver
Enter fullscreen mode Exit fullscreen mode

Now, head to your browser and type for localhost:8000 or 'CRTL + Left click' the link at the terminal.

Image description

Image description

Note: If you're having trouble with the Pytube module about the AttributeError: 'NoneType' object has no attribute 'span', here are some discussions in Stack Overflow and Github that might be helpful for you.

Well if everything works fine, you can now enjoy downloading youtube videos for free, and access them anytime you want. For more information about the pytube module, click here. Have a nice day!!

Top comments (0)