Upload and Play Video using Django

Here I am going to show you how to upload and play video using Django framework in Python programming. The uploaded video may or may not be played automatically but the uploaded video will have controls, such as, paly, pause, full screen, mute, unmute, download, etc.

An upload form is displayed to the end user for browsing and selecting a video file that will be uploaded and displayed on the browser. I am using HTML5 tag to play the video. Make sure your browser supports HTML5 tag for playing video.

Prerequisites

Python: 3.9.5, Django: 3.2.4

Project Setup

You generally create a Django project anywhere on your system and under your Django project you have one or more applications.

Let’s say you have created Django project directory called djangovideouploaddisplay and you have also created an app called videouploaddisplay under djangovideouploaddisplay. You may check the documentation for creating Django project and apps under project.

I assume you have the required configurations for your videouploaddisplay in djangovideouploaddisplay/djangovideouploaddisplay/settings.py file under INSTALLED_APPS section as below:

INSTALLED_APPS = [
    ...
    'videouploaddisplay.apps.VideouploaddisplayConfig',
]

The videouploaddisplay.apps.VideouploaddisplayConfig is formed as a dotted notation from djangovideouploaddisplay/videouploaddisplay/apps.py, where you will find the class name as VideouploaddisplayConfig that has name videouploaddisplay.

In your settings file – djangovideouploaddisplay/djangovideouploaddisplay/settings.py, define MEDIA_ROOT and MEDIA_URL, for example:

MEDIA_ROOT = os.path.join(BASE_DIR, '')

MEDIA_URL = '/'

In the above configuration I am not specifying any directory for storing the video but the video will be uploaded in the root directory of the project.

upload and play video using django

Template or View File

The template or view file is nothing but you write code on HTML file what you want to display on UI (User Interface). For this video file upload functionality I am going to put only one field that is file which will be used for browsing and selecting file.

The name of the below template file is upload-display-video.html and put it under videouploaddisplay/templates directory.

<!DOCTYPE html>
<html>
    <head>
        <title>Django - Video File Upload and Display</title>
    </head>
    <body>
		<div style="width: 500px; margin: auto;">
			<fieldset name="Video File Upload and Display">
				{% if msg %} {% autoescape off %} {{ msg }} {% endautoescape %} {% endif %}
				<form method="post" action="/" enctype="multipart/form-data">
					{% csrf_token %}
					<dl>
						<p>
							<label>Browse and select a video file</label>&nbsp;&nbsp;
							<input type="file" name="file" autocomplete="off" required>
						</p>
					</dl>
					<p>
						<input type="submit" value="Upload and Display">
					</p>
				</form>
			</fieldset>
			
			{% if filename %}
				<div style="margin: 10px auto;">
					<video autoplay="autoplay" controls="controls" preload="preload">
						<source src="{{ MEDIA_URL }}/{{ filename }}" type="video/mp4"></source>
					</video>
				</div>
			{% endif %}
		</div>	
    </body>
</html>

In the above file user selects a video file and if file gets successfully uploaded into the root directory of the project folder then below the upload form I am displaying the video that will starts playing automatically.

The another important thing is you need to set CSRF token on the form using {% csrf_token %} otherwise you won’t be able to upload file and you would get the following errors:

CSRF token is not set

CSRF Token missing or incorrect

You also need to ensure to check the CSRF token on your server side code and you will later when you go through the code in views.py file.

Form

The Django Form will map the fields to form on your template file. In the above template or view file I have kept only one field called file which is used to select a file. A view handling this form will receive data into request.FILES.

request.FILES will only contain data if the HTTP request method is POST, at least one file is posted and the corresponding form has an attribute enctype="multipart/form-data", because dealing with forms that have FileField and ImageField fields are more complex.

The following code snippets are written into forms.py file under directory videouploaddisplay.

from django import forms

class UploadFileForm(forms.Form):
    file = forms.FileField()

Views

In this view I am going to show how to upload file into a server location. You will also see how file data is passed from request to Form. Here also notice how I have used CSRF decorator to ensure the CSRF token.

from django.shortcuts import render
from .forms import UploadFileForm
from django.views.decorators.csrf import ensure_csrf_cookie

@ensure_csrf_cookie
def upload_display_video(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            file = request.FILES['file']
            #print(file.name)
            handle_uploaded_file(file)
            return render(request, "upload-display-video.html", {'filename': file.name})
    else:
        form = UploadFileForm()
    return render(request, 'upload-display-video.html', {'form': form})

def handle_uploaded_file(f):
    with open(f.name, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

Note that you have to pass request.FILES into the Form‘s constructor to bind the file data into a Form.

Looping over UploadedFile.chunks() instead of using read() ensures that large files don’t overwhelm your system’s memory.

Ideally the function handle_uploaded_file() should be put into common utility file, but just for the sake of this example I have kept into the same file videouploaddisplay/views.py.

Before you save the file onto disk the uploaded file data is stored under the tmp folder and the file name is generated something like tmpzfp312.upload. If the file size is up to 2.5 MB then file is not saved under the tmp folder and entire content is read from the memory and the reading becomes very fast.

URLs

Now you need to define the path or URL which will call the appropriate function (for this example, upload_display_video()) on your views.py file. You need to create a file urls.py under videouploaddisplay folder with the following code snippets.

from django.urls import path
from django.conf import settings

from . import views

urlpatterns = [
    path('', views.upload_display_video, name='upload_display_video'),
]

I want to upload and display video on root URL, so I did not mention any path on the URL.

The path() function is passed four arguments, two required: route and view, and two optional: kwargs, and name.

route is a string that contains a URL pattern.

view calls the specified view function with an HttpRequest object as the first argument and any “captured” values from the route as keyword arguments.

kwargs are arbitrary keyword arguments can be passed in a dictionary to the target view.

name – naming your URL lets you refer to it unambiguously from elsewhere in Django, especially from within templates.

Another important thing you need to do is to configure the URL into the project. This (videouploaddisplay) is an app and your project does not know anything about this URL. So add the following line into djangovideouploaddisplay/djangovideouploaddisplay/urls.py file under urlpatterns = [...].

path('', include('videouploaddisplay.urls')),

You need to also include the MEDIA_URL which you defined earlier in settings.py file. The complete content for this djangovideouploaddisplay/djangovideouploaddisplay/urls.py file is given below:

#from django.contrib import admin
from django.conf import settings
from django.urls import path, include
from django.conf.urls.static import static

urlpatterns = [
    #path('admin/', admin.site.urls),
    path('', include('videouploaddisplay.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Deploying Application

Now I am ready to test the app I have built. Let’s fire up the server from the command line using manage.py runserver. The application will run on default port 8000. If you want to change the default host/port of the server then you can read tutorial How to change default host/port in Django.

Testing the Application

When you hit URL http://localhost:8000 on browser, your home page looks similar to the following image:

upload and play video using django

When you upload a video your video will be started playing automatically. Hovering the video will display the controls for video.

upload and play video using django

That’s all about how to upload and play video using Django in Python.

Source Code

Download

Leave a Reply

Your email address will not be published.