CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-cloudinary

Python and Django SDK for Cloudinary, a cloud-based image and video management service with comprehensive transformation, optimization, and delivery capabilities

Overall
score

94%

Overview
Eval results
Files

django-integration.mddocs/

Django Integration

Complete Django framework integration including model fields, form widgets, template tags, and admin interface components.

Capabilities

Model Fields

Django model field for storing Cloudinary resource references.

class CloudinaryField(models.Field):
    """Django model field for Cloudinary resources.
    
    Stores Cloudinary resource information as a JSON-serializable format and
    provides easy access to resource URLs and transformations.
    """
    
    def __init__(self, type="upload", resource_type="image", **options):
        """Initialize CloudinaryField.
        
        Args:
            type (str, optional): Delivery type ('upload', 'private', 'authenticated')
            resource_type (str, optional): Resource type ('image', 'video', 'raw', 'auto')
            **options: Additional field options
        """
    
    def get_internal_type(self):
        """Get the internal field type for Django."""
    
    def to_python(self, value):
        """Convert database value to Python CloudinaryResource object.
        
        Args:
            value: Database value (string, dict, or CloudinaryResource)
        
        Returns:
            CloudinaryResource: Cloudinary resource object or None
        """
    
    def from_db_value(self, value, expression, connection):
        """Convert database value to Python object."""
    
    def get_prep_value(self, value):
        """Convert Python value to database-storable format."""
    
    def value_to_string(self, obj):
        """Convert field value to string representation."""
    
    def formfield(self, **kwargs):
        """Return appropriate form field for this model field."""

Form Fields and Widgets

Django form components for handling Cloudinary uploads.

class CloudinaryInput(forms.TextInput):
    """Text input widget for Cloudinary resource public IDs.
    
    Provides a simple text input for entering Cloudinary public IDs manually.
    """
    
    def __init__(self, attrs=None):
        """Initialize the input widget.
        
        Args:
            attrs (dict, optional): HTML attributes for the input element
        """

class CloudinaryFileField(forms.FileField):
    """File field that uploads to Cloudinary on form submission.
    
    Handles file uploads to Cloudinary and returns the uploaded resource information.
    """
    
    def __init__(self, **options):
        """Initialize the file field.
        
        Args:
            **options: Cloudinary upload options (same as uploader.upload())
        """
    
    def to_python(self, data):
        """Process uploaded file and upload to Cloudinary."""

class CloudinaryJsFileField(forms.Field):
    """JavaScript-based file field for direct browser uploads.
    
    Uses Cloudinary's JavaScript upload widget for direct browser-to-Cloudinary uploads
    without going through your server.
    """
    
    def __init__(self, **options):
        """Initialize the JavaScript file field.
        
        Args:
            **options: Upload widget configuration options
        """

class CloudinaryUnsignedJsFileField(CloudinaryJsFileField):
    """JavaScript file field for unsigned uploads using upload presets.
    
    Allows uploads without server-side signature generation using predefined upload presets.
    """
    
    def __init__(self, upload_preset, **options):
        """Initialize the unsigned JavaScript file field.
        
        Args:
            upload_preset (str): Name of the upload preset to use
            **options: Additional upload widget options
        """

Template Tags

Django template tags for generating Cloudinary URLs and HTML elements.

def cloudinary_url(public_id, **options):
    """Template tag for generating Cloudinary URLs.
    
    Usage in templates:
        {% load cloudinary %}
        {% cloudinary_url "sample" width=300 height=200 crop="fill" %}
    
    Args:
        public_id (str): Public ID of the resource
        **options: Transformation and URL generation options
    
    Returns:
        str: Generated Cloudinary URL
    """

def cloudinary_tag(public_id, **options):
    """Template tag for generating Cloudinary image tags.
    
    Usage in templates:
        {% load cloudinary %}
        {% cloudinary_tag "sample" width=300 height=200 crop="fill" alt="Sample" %}
    
    Args:
        public_id (str): Public ID of the resource
        **options: Transformation options and HTML attributes
    
    Returns:
        str: HTML img tag with Cloudinary URL
    """

def cloudinary_direct_upload_field(form_field, **options):
    """Template tag for direct upload fields.
    
    Usage in templates:
        {% cloudinary_direct_upload_field form.image %}
    
    Args:
        form_field: Django form field instance
        **options: Upload widget options
    
    Returns:
        str: HTML for direct upload widget
    """

def cloudinary_includes():
    """Template tag for including Cloudinary JavaScript files.
    
    Usage in templates:
        {% cloudinary_includes %}
    
    Returns:
        str: HTML script tags for Cloudinary JavaScript
    """

def cloudinary_js_config():
    """Template tag for JavaScript configuration.
    
    Usage in templates:
        {% cloudinary_js_config %}
    
    Returns:
        str: JavaScript configuration object
    """

def cloudinary_direct_upload(callback_url=None, **options):
    """Template tag for direct upload configuration.
    
    Usage in templates:
        {% cloudinary_direct_upload callback_url="/upload_complete/" %}
    
    Args:
        callback_url (str, optional): URL to call after upload completion
        **options: Upload configuration options
    
    Returns:
        str: JavaScript for direct upload setup
    """

Form Initialization

Helper functions for setting up forms with Cloudinary integration.

def cl_init_js_callbacks(form, request):
    """Initialize JavaScript callbacks for Cloudinary forms.
    
    Args:
        form: Django form instance
        request: Django request object
    
    Returns:
        str: JavaScript initialization code
    """

Usage Examples

Model Definition

from django.db import models
from cloudinary.models import CloudinaryField

class Product(models.Model):
    """Product model with Cloudinary image fields."""
    
    name = models.CharField(max_length=100)
    description = models.TextField()
    
    # Single image field
    image = CloudinaryField('image', null=True, blank=True)
    
    # Video field
    video = CloudinaryField('video', resource_type='video', null=True, blank=True)
    
    # Private image field
    private_image = CloudinaryField('image', type='private', null=True, blank=True)
    
    # Raw file field
    document = CloudinaryField('raw', resource_type='raw', null=True, blank=True)
    
    def __str__(self):
        return self.name
    
    def get_image_url(self, **options):
        """Get transformed image URL."""
        if self.image:
            return self.image.build_url(**options)
        return None
    
    def get_thumbnail_url(self):
        """Get thumbnail URL."""
        return self.get_image_url(
            width=300,
            height=300,
            crop="fill",
            quality="auto"
        )

# Usage in views
def product_detail(request, product_id):
    product = Product.objects.get(id=product_id)
    
    # Access Cloudinary resource
    if product.image:
        image_url = product.image.build_url(width=800, height=600, crop="fit")
        thumbnail_url = product.image.build_url(width=200, height=200, crop="thumb")
    
    return render(request, 'product_detail.html', {
        'product': product,
        'image_url': image_url,
        'thumbnail_url': thumbnail_url
    })

Form Definition

from django import forms
from cloudinary.forms import CloudinaryFileField, CloudinaryJsFileField, CloudinaryUnsignedJsFileField
from .models import Product

class ProductForm(forms.ModelForm):
    """Form for creating/editing products with Cloudinary uploads."""
    
    class Meta:
        model = Product
        fields = ['name', 'description', 'image', 'video']
    
    # Override with Cloudinary file field
    image = CloudinaryFileField(
        options={
            'tags': 'product_image',
            'folder': 'products',
            'transformation': [
                {'width': 1000, 'height': 1000, 'crop': 'limit'},
                {'quality': 'auto', 'format': 'auto'}
            ],
            'eager': [
                {'width': 300, 'height': 300, 'crop': 'thumb'},
                {'width': 800, 'height': 600, 'crop': 'fit'}
            ]
        }
    )

class ProductJsForm(forms.ModelForm):
    """Form using JavaScript-based direct uploads."""
    
    class Meta:
        model = Product
        fields = ['name', 'description', 'image']
    
    # JavaScript upload field
    image = CloudinaryJsFileField(
        options={
            'tags': 'js_upload',
            'folder': 'products',
            'resource_type': 'image',
            'format': 'auto',
            'quality': 'auto'
        }
    )

class ProductUnsignedForm(forms.ModelForm):
    """Form using unsigned uploads with preset."""
    
    class Meta:
        model = Product
        fields = ['name', 'description', 'image']
    
    # Unsigned upload field
    image = CloudinaryUnsignedJsFileField(
        'product_preset',  # Upload preset name
        options={
            'tags': 'unsigned_upload',
            'folder': 'products'
        }
    )

Template Usage

<!-- Load Cloudinary template tags -->
{% load cloudinary %}

<!-- Include Cloudinary JavaScript (required for JS uploads) -->
{% cloudinary_includes %}

<!-- Display image with transformations -->
{% if product.image %}
    {% cloudinary_tag product.image.public_id width=400 height=300 crop="fill" alt=product.name class="img-responsive" %}
{% endif %}

<!-- Generate URL only -->
{% cloudinary_url product.image.public_id width=800 height=600 crop="fit" as large_image_url %}
<a href="{{ large_image_url }}" target="_blank">View Large Image</a>

<!-- Form with direct upload -->
<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    
    {{ form.name.label_tag }}
    {{ form.name }}
    
    {{ form.description.label_tag }}
    {{ form.description }}
    
    <!-- Direct upload field -->
    {% cloudinary_direct_upload_field form.image %}
    
    <button type="submit">Save Product</button>
</form>

<!-- JavaScript configuration -->
{% cloudinary_js_config %}

<!-- Responsive image with breakpoints -->
{% cloudinary_tag product.image.public_id width=800 height=600 crop="fill" responsive=True class="img-responsive" %}

Advanced Template Examples

<!-- Conditional image display -->
{% if product.image %}
    <div class="product-image">
        {% cloudinary_tag product.image.public_id width=500 height=400 crop="fill" quality="auto" format="auto" alt=product.name %}
        
        <!-- Thumbnail gallery -->
        <div class="thumbnails">
            {% cloudinary_tag product.image.public_id width=100 height=100 crop="thumb" %}
            {% cloudinary_tag product.image.public_id width=100 height=100 crop="thumb" effect="sepia" %}
            {% cloudinary_tag product.image.public_id width=100 height=100 crop="thumb" effect="grayscale" %}
        </div>
    </div>
{% else %}
    <div class="no-image">
        <p>No image available</p>
    </div>
{% endif %}

<!-- Video with poster image -->
{% if product.video %}
    <video controls width="640" height="480" 
           poster="{% cloudinary_url product.video.public_id resource_type='video' format='jpg' %}">
        <source src="{% cloudinary_url product.video.public_id resource_type='video' format='mp4' %}" type="video/mp4">
        <source src="{% cloudinary_url product.video.public_id resource_type='video' format='webm' %}" type="video/webm">
    </video>
{% endif %}

View Integration

from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import ProductForm, ProductJsForm
from .models import Product

def create_product(request):
    """Create product with Cloudinary upload."""
    
    if request.method == 'POST':
        form = ProductForm(request.POST, request.FILES)
        if form.is_valid():
            product = form.save()
            
            # Access uploaded image information
            if product.image:
                print(f"Uploaded image: {product.image.public_id}")
                print(f"Image URL: {product.image.url}")
                print(f"Secure URL: {product.image.build_url(secure=True)}")
            
            messages.success(request, 'Product created successfully!')
            return redirect('product_detail', product_id=product.id)
    else:
        form = ProductForm()
    
    return render(request, 'create_product.html', {'form': form})

def product_gallery(request):
    """Display product gallery with various transformations."""
    
    products = Product.objects.filter(image__isnull=False)
    
    # Prepare image variations
    product_images = []
    for product in products:
        if product.image:
            product_images.append({
                'product': product,
                'thumbnail': product.image.build_url(width=200, height=200, crop="thumb"),
                'medium': product.image.build_url(width=400, height=300, crop="fill"),
                'large': product.image.build_url(width=800, height=600, crop="fit"),
            })
    
    return render(request, 'product_gallery.html', {
        'product_images': product_images
    })

Django Settings Configuration

# settings.py
import cloudinary

# Cloudinary configuration
cloudinary.config(
    cloud_name="your_cloud_name",
    api_key="your_api_key",
    api_secret="your_api_secret",
    secure=True
)

# Optional: Default upload parameters
CLOUDINARY_STORAGE = {
    'CLOUD_NAME': 'your_cloud_name',
    'API_KEY': 'your_api_key',
    'API_SECRET': 'your_api_secret'
}

# Template context processors (if using template tags)
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

# Add cloudinary to INSTALLED_APPS
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'cloudinary',
    'your_app',
]

Install with Tessl CLI

npx tessl i tessl/pypi-cloudinary

docs

admin-api.md

configuration.md

django-integration.md

exceptions.md

index.md

provisioning-api.md

search-api.md

transformations.md

upload-api.md

tile.json