In this Python Django tutorial, I will explain how to validate URL string in Python Django in simple steps.
I’ve been developing a website to download YouTube videos recently using the Django web framework. Additionally, I must validate URL string in Python Django project.
In order to download the YouTube video into your internal system and validate its URL string, I carried out the research and built the logic.
Here, we will see:
- What is pytube library?
- How to use pytube
- Setup project using Django web framework
- How to validate URL string in Python Django
- YouTube video downloader using Python Django
At the end of this article, you can also download the code given to validate URL string in Python Django.
This is what we will build here.
How to validate URL string in Python Django
Now, let us first understand the pytube library and learn step-by-step to download YouTube videos and validate URL strings in Python Django.
pytube library
YouTube is a well-known platform for sharing videos. It requires effort to download a video from YouTube. This task is fairly simple to complete with Python Django
There is a Python library called pytube that can do this. It is a lightweight, dependency-free Python library that is used to handle YouTube video downloading.
How to set up pytube library
pytube is not an in-built library, we need to install it before using it in our activated virtual environment. Now, install it using the below-given command.
pip install pytube
How to validate URL string and built YouTube video downloader
Now, we will see an example to validate URL string and download YouTube Videos in Python Django.
Read: Python Django form validation
Set up Project in Django web framework
To start a Django project, open the terminal and enter the following command. Here, YouTubeURLValidator is the name of the Django Project.
django-admin startproject YouTubeURLValidator
It will make a folder called YouTubeURLValidator and to enter the project, type the below command in the terminal.
cd YouTubeURLValidator
Create a Django app named MyApp inside this project folder, by typing the below command in the terminal.
python manage.py startapp MyApp
Add the app name to the INSTALLED_APP list located in the settings.py file, to activate this app.
Django includes a urls.py file in the project directory to map the newly constructed app inside of it, by default. To do so, add the below code in it.
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('MyApp.urls')),
]
Read: How to Create model in Django
Create Form using Python Django
To create the form in Django which takes the YouTube URLs from the user to validate the URL string and download the video, we create the forms.py file and the below-given code.
from django import forms
class YouTubeForm(forms.Form):
video_url = forms.CharField()
- Here, we create the form using the Form class named YouTubeForm.
- It consists of CharField named video_url which is used to take the YouTube video URL.
Django Template to validate URL string in Python Django and download YouTube video
Since the front end of a Django application is specified as Templates. Create a subdirectory called Templates in the main project directory to store all of the project template files.
Open the settings.py file to update the DIRS to use the Templates folder’s path.
Create a home.html file to add the HTML code for downloading the YouTube video, inside the Template folder.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Video Downloader</title>
<style>
table {
border: 8px outset;
border-radius: 10px;
border-spacing: 10px;
padding: 20px;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
<h1 align="center">PythonGuides Video Downloader</h1>
<hr>
<h3 align="center">Please provide the URL of the YouTube video which you want to download.</h3>
<hr>
<br>
{% if messages %}
{% for message in messages %}
<div class="alert alert-primary" role="alert">
<p{% if message.tags %} class="" {% endif %}>{{ message }}</p>
</div>
{% endfor %}
{% endif %}
<form method="post">
{% csrf_token %}
<table>
{{form.as_table}}
</table>
<br><br>
<div style="text-align:center">
<button type="submit">Download</button>
</div>
</form>
</body>
</html>
- The table’s style is first defined in the head tag.
- The HTML tags h1 and h3 are then used to add the heading for the form inside the body tag.
- Use the br and hr tags, respectively, to break the line and draw a horizontal line.
- We utilize the message tag in the if and for statement to output the invalid URL error message.
- Next, we use the csrf_token included within the form element to protect the form from cyberattacks and allow us to securely communicate the data.
- The form is then rendered as a table within the table using the form.as_table tag.
- Add a submit button lastly to allow the user to download YouTube videos.
Create a success.html file to add the HTML code for showing the success message of URL validation and downloading the YouTube video, inside the Template folder.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Success</title>
</head>
<body>
<h1 align="center">PythonGuides Video Downloader</h1>
<hr>
<h3 align="center">Thanking You for visting!!! Video downloaded succesfully.</h3>
<hr>
<br>
{% if messages %}
{% for message in messages %}
<div class="alert alert-primary" role="alert">
<p{% if message.tags %} class="" {% endif %}>{{ message }}</p>
</div>
{% endfor %}
{% endif %}
<p>
Want to download more YouTube video: <a href="{% url 'urlvalidate' %}">Click Here</a>
</p>
</body>
</html>
- The HTML tags h1 and h3 are then used to add the heading for the form inside the body tag.
- Use the br and hr tags, respectively, to break the line and draw a horizontal line.
- We utilize the message tag in the if and for statement to output the success message of the video downloading.
- Next, we add the link to go back to the home page for another video downloading using a href tag within the p tag.
Read: Python Django MySQL CRUD
Define Django View
To define the main logic for the application, open the views.py file and add the code given below.
from django.shortcuts import render
from pytube import YouTube
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
from django.contrib import messages
from .forms import YouTubeForm
# Create your views here.
def urlvalidate(request):
if request.method == 'POST':
form = YouTubeForm(request.POST)
if form.is_valid():
video_url = form.cleaned_data['video_url']
valiadte = URLValidator()
try:
valiadte(video_url)
messages.info(request,'URL valiadte successfully')
video = YouTube(video_url)
download_video = video.streams.get_lowest_resolution()
download_video.download()
return render(request, "success.html")
except ValidationError as exception:
print(exception)
messages.info(request,exception)
form = YouTubeForm()
return render(request, "home.html", {'form':form})
- Here, we create a view called urlvalidate that retrieves the video_url from the form, checks it using the validate function, and outputs a success message if validation was successful or a validation error if it wasn’t.
- Additionally, upon validation success, we use YouTube function to download the YouTube video whose link we entered in the video_url field. The get_lowest_resolution method is then used to stream the video.
- We also use the download method to download the video internally, and after the video downloads successfully, we render to the success page.
Now, we must map the view with the URL in order to call it, thus we must create a file called urls.py in the app directory. Include the code below in it.
from django.urls import path
from . import views
urlpatterns = [
path('', views.urlvalidate, name='urlvalidate'),
]
This is how we can validate URL string in Python Django and build a YouTube downloader.
Read: Create Contact Form with Django and SQLite
Execute Django Project
To launch a development server type the below-given command in the terminal.
python manage.py runserver
It successfully opens the Django page, to enter the URL string in Python Django. Then, click on Download.
It successfully redirects us to the success page which shows the validation success message. If you want to download more YouTube videos to your internal storage, simply click on the Click Here link.
If we enter, the incorrect URL, it will show us the error message that the URL is invalid.
Read: Build a Django Contact Form with Email
Download Validate URL string in Python Django complete code
Here is the code.
Conclusion
With this, we have successfully learned to check if a string is a valid URL in Python Django. We have also learned about pytube library and to build a YouTube downloader website using the Django web framework.
Additionally, we have also covered the following topics.
- What is pytube library?
- How to use pytube
- Setup project using Django web framework
- How to validate URL string in Python Django
- YouTube video downloader using Python Django
You may also like to read the following Python Django tutorials.
- Get URL parameters in Django
- Django get all data from POST request
- If statement in Django template
- Python Django random number
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.