Django image and video upload
Cloudinary provides an API for uploading images, videos, and any other kind of file to the cloud. Files uploaded to Cloudinary are stored safely in the cloud with secure backups and revision history. Cloudinary's APIs allow secure uploading from your servers, directly from your visitors' browsers or mobile applications, or fetched via remote public URLs.
Cloudinary's Django SDK wraps Cloudinary's upload API and simplifies the integration. Django methods are available for easily performing Django image and video uploads to the cloud and Django view helper methods are available for uploading directly from a browser to Cloudinary.
This page covers common usage patterns for Django image and video upload with Cloudinary.
For details on all available upload options and parameters, see the Media upload documentation, and the Upload method of the Upload API Reference.
Upload widget
Cloudinary's Upload widget is an interactive, feature rich, simple-to-integrate user interface that enables you to add Cloudinary upload support to your website. The widget can be easily embedded in your web application with just a few lines of JavaScript code, eliminating the need to develop in-house interactive upload capabilities. See the Upload widget documentation for detailed information.
Server-side upload
You can upload images, videos, or any other raw file to Cloudinary from your Django or Python code. Uploading is done over HTTPS using a secure protocol based on your account's api_key
and api_secret
parameters.
Django image upload
The following method uploads an image to the cloud:
For example, uploading a local image file named 'my_image.jpg':
The file to upload can be specified as a local path, a remote HTTP or HTTPS URL, a whitelisted storage bucket (S3 or Google Storage) URL, a base-64 data URI, or an FTP URL. For details, see File source options.
For details on all available upload options and parameters, see the Media upload documentation, and the Upload method of the Upload API Reference.
Django video upload
You upload videos in exactly the same way as images. However, the upload
method supports uploading files only up to 100 MB. To upload larger videos, use the upload_large method, which uploads large files to the cloud in chunks.
The upload_large
method has the identical signature and options as the upload
method, with the addition of an optional chunk_size
parameter (default 20 MB).
The following example uploads dog.mp4
to Cloudinary and stores it in a bi-level folder structure with the public ID dog_closeup
. It also performs two eager transformations that resize the video to a square and a small rectangle.
cloudinary.uploader.upload_large("dog.mp4", resource_type = "video", public_id = "my_folder/my_sub_folder/dog_closeup", chunk_size = 6000000, eager = [ { "width": 300, "height": 300, "crop": "pad", "audio_codec": "none"}, { "width": 160, "height": 100, "crop": "crop", "gravity": "south", "audio_codec": "none"}], eager_async = true, eager_notification_url = "https://mysite.example.com/notify_endpoint")
Upload response
By default, uploading is performed synchronously. Once finished, the uploaded image or video is immediately available for manipulation and delivery. An upload call returns a Hash with content similar to the following:
{ u'bytes': 29802, u'created_at': u'2017-06-25T17:20:30Z', u'format': u'jpg', u'height': 282, u'public_id': u'hl22acprlomnycgiudor', u'resource_type': u'image', u'secure_url': u'https://res.cloudinary.com/demo/image/upload/v1571218039/hl22acprlomnycgiudor.jpg', u'signature': u'10594f028dbc23e920fd084f8482394798edbc68', u'type': u'upload', u'url': u'http://res.cloudinary.com/demo/image/upload/v1571218039/hl22acprlomnycgiudor.jpg', u'version': 1571218039, u'width': 292 }
upload_resource
method (which is identical to the upload method except for the response).The response includes HTTP and HTTPS URLs for accessing the uploaded media asset as well as additional information regarding the uploaded asset: The Public ID, resource type, width and height, file format, file size in bytes, a signature for verifying the response and more.
Data uploading options
Cloudinary's Python library supports uploading files from various sources.
You can upload an image by specifying a local path of an image file. For example:
You can provide an IO object that you created:
If your images are already publicly available online, you can specify their remote HTTP URLs instead of uploading the actual data. In this case, Cloudinary will fetch the image from its remote URL for you. This option allows for a much faster migration of your existing images. Here's an example:
If you have existing images in an Amazon S3 bucket, you can point Cloudinary to their S3 URLs. Note - this option requires a quick manual setup. Contact us and we'll guide you on how to allow Cloudinary access to your relevant S3 buckets.
In cases where images are uploaded by users of your Django application through a web form, you can pass the parameter of your Django's request.FILES to the upload method:
Django forms and models
You can integrate Cloudinary's uploading capabilities with your Django models and forms using Cloudinary's helper classes. As shown in the example below, you can define a model class Photo
in your models.py
file. This class has an image
field of the CloudinaryField
class.
from django.db import models from cloudinary.models import CloudinaryField class Photo(models.Model): image = CloudinaryField('image')
In the forms.py
file we define a PhotoForm
class that has a form field named image
of the CloudinaryFileField
class (by default).
from django.forms import ModelForm from .models import Photo class PhotoForm(ModelForm): class Meta: model = Photo
The views.py
file defines a view named upload
which displays a HTML upload form and also handles posting of image files. Such images are uploaded to Cloudinary from your Django server by the CloudinaryFileField
class.
from django import forms from django.http import HttpResponse from cloudinary.forms import cl_init_js_callbacks from .models import Photo from .forms import PhotoForm def upload(request): context = dict( backend_form = PhotoForm()) if request.method == 'POST': form = PhotoForm(request.POST, request.FILES) context['posted'] = form.instance if form.is_valid(): form.save() return render(request, 'upload.html', context)
The following HTML templates includes a form that uploads images to your server for uploading to Cloudinary:
{% load cloudinary %} {% load url from future %} {% block body %} <div id='backend_upload'> <form action="{% url "photo_album.views.upload" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ backend_form }} <input type="submit" value="Upload"> </form> </div> {% endblock %}
Having stored the image ID, you can now embed the image or a transformed version of it using the cloudinary
template tag:
{% load cloudinary %} {% cloudinary photo.image format="jpg" width=120 height=80 crop="fill" %}
In addition, you can assign tags, apply transformation or specify any Cloudinary's upload options when initializing the CloudinaryFileField
class.
from django.forms import ModelForm from cloudinary.forms import CloudinaryFileField from .models import Photo class PhotoForm(ModelForm): class Meta: model = Photo image = CloudinaryFileField( attrs = { 'style': "margin-top: 30px" }, options = { 'tags': "directly_uploaded", 'crop': 'limit', 'width': 1000, 'height': 1000, 'eager': [{ 'crop': 'fill', 'width': 150, 'height': 100 }] })
- For more information on uploading media assets, see the Media upload documentation.
- For details on all available upload parameters, see the Upload method of the Upload API Reference.
Direct uploading from the browser
The upload samples shown above allow your server-side Django code to upload media assets to Cloudinary. In this flow, if you have a web form that allows your users to upload images or videos, the media file's data is first sent to your server and then uploaded to Cloudinary.
A more efficient and powerful option is to allow your users to upload images and videos in your client-side code directly from the browser to Cloudinary instead of going through your servers. This method allows for faster uploading and a better user experience. It also reduces load from your servers and reduces the complexity of your Django applications.
You can upload files directly from the browser using signed or unsigned calls to the upload endpoint, as shown in Example: Upload multiple files using a form.
Alternatively, you can use Cloudinary's jQuery plugin as described in the following sections.
For signed uploads from your client-side code, a secure signature must be generated in your server-side Django code. You can use the api_sign_request
method to generate SHA-1 signatures:
jQuery uploading environment setup
Start by including the required Javascript files: Cloudinary's jQuery plugin as well as the jQuery-File-Upload plugin it depends on. These are located in the cloudinary/static
folder of the Django library, as well as in the js
folder of Cloudinary's Javascript library.
In your Django template, load Cloudinary and include jQuery and the required jQuery plugins:
{% load cloudinary %}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
{% cloudinary_includes %}
Cloudinary's jQuery plugin requires your cloud_name
and additional optional configuration parameters.
api_secret
in public client-side code.To automatically set-up Cloudinary's configuration, include the following line in your view or layout:
The Cloudinary jQuery library utilizes the Blueimp File Upload library to support uploading media directly from the browser. You must explicitly initialize this library:
$(function() { if($.fn.cloudinary_fileupload !== undefined) { $("input.cloudinary-fileupload[type=file]").cloudinary_fileupload(); } });
cloudinary_cors.html
is automatically used to enable cross browser uploads when CORS is not supported. See the usage of cl_init_js_callbacks
in the samples below.jQuery upload file tag
Cloudinary's direct uploading can be integrated with your Django model. The following example assumes you have the Photo
class defined in your models.py
file. The Photo
class has an image
field of the CloudinaryField
class.
from django.db import models from cloudinary.models import CloudinaryField class Photo(models.Model): image = CloudinaryField('image')
In the forms.py
file, define a PhotoDirectForm
class that has a form field named image of the CloudinaryJsFileField
class. This class does all the behind-the-scenes work for you.
from django.forms import ModelForm from cloudinary.forms import CloudinaryJsFileField from .models import Photo class PhotoDirectForm(ModelForm): class Meta: model = Photo image = CloudinaryJsFileField()
The views.py
file defines a view named upload_prompt
, which initializes the direct form and defines the required callback URL:
from django import forms from django.http import HttpResponse from cloudinary.forms import cl_init_js_callbacks from .models import Photo from .forms import PhotoDirectForm def upload_prompt(request): context = dict(direct_form = PhotoDirectForm()) cl_init_js_callbacks(context['direct_form'], request) return render(request, 'upload_prompt.html', context)
Embed a file input tag in your HTML templates using the cloudinary_direct_upload_field
template tag or the direct_form
you defined. The following example adds a file input field to your form. Selecting or dragging a file to this input field automatically initiates uploading from the browser to Cloudinary.
<form action="{% url "photo_album.views.direct_upload_complete" %}" method="post"> {% csrf_token %} {{ direct_form }} {# alternatively, use: {% cloudinary_direct_upload_field "image", request=request %} #} <input type="submit" value="Submit" /> </form>
When uploading is completed, the identifier of the uploaded image is set as the value of a hidden input field with the specified name. You can then process the identifier received by your Django code and store it in your model for future use, exactly as if you're using standard server-side uploading.
The following Django code in views.py
processes the received identifier, verifies the signature (concatenated to the identifier) and updates a model entity with the identifiers of the uploaded image (i.e., the Public ID and version of the image).
import json from django import forms from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from .models import Photo from .forms import PhotoDirectForm ... @csrf_exempt def direct_upload_complete(request): form = PhotoDirectForm(request.POST) if form.is_valid(): form.save() ret = dict(photo_id = form.instance.id) else: ret = dict(errors = form.errors) return HttpResponse(json.dumps(ret), content_type='application/json')
Having stored the image ID, you can now display a directly uploaded image in the same way you would display any other Cloudinary hosted image:
{% load cloudinary %} {% cloudinary photo.image format="jpg" width=120 height=80 crop="fill" %}
Additional jQuery uploading options
When uploading directly from the browser using signed upload, you can still specify all the upload options available to server-side uploading.
For example, the following call performs direct uploading that will also tag the uploaded image, limit its size to given dimensions and generate a thumbnail eagerly. Also notice the custom HTML attributes.
from django.forms import ModelForm from cloudinary.forms import CloudinaryJsFileField from .models import Photo class PhotoDirectForm(ModelForm): class Meta: model = Photo image = CloudinaryJsFileField( attrs = { 'style': "margin-top: 30px" }, options = { 'tags': "directly_uploaded", 'crop': 'limit', 'width': 1000, 'height': 1000, 'eager' [{ 'crop': 'fill', 'width': 150, 'height': 100 }] })
For the full list of parameters available for signed uploads, see the Upload method in the Upload API Reference.
Additional jQuery library features
Cloudinary's jQuery library also enables an enhanced uploading experience with options like showing a progress bar, displaying a thumbnail of the uploaded image, drag & drop support, uploading multiple files and more.
For example, bind to Cloudinary's cloudinarydone
event if you want to be notified when an upload to Cloudinary has completed. You will have access to the full details of the uploaded image and you can display a cloud-generated thumbnail of the uploaded images using Cloudinary's jQuery plugin. The following code creates a 150x100 thumbnail of an uploaded image and updates an input field with the public ID of this image.
$('.cloudinary-fileupload').bind('cloudinarydone', function(e, data) { $('.preview').html( $.cloudinary.image(data.result.public_id, { format: data.result.format, version: data.result.version, crop: 'fill', width: 150, height: 100 }) ); $('.image_public_id').val(data.result.public_id); return true; });
You can find more details and options in the jQuery documentation.
- For more information on uploading media assets, see the Media upload documentation.
- For details on all available upload parameters, see the Upload method of the Upload API Reference.