uploadcaredocs

Django Integration
20 Minutes to Integrate

Uploadcare is an end-to-end file API that allows you to fully manage file uploads, storage, transformations, and delivery. All that is included in our Python and Django integrations.

In this guide, we will create an app with an Instagram-like grid feed and image uploading:

The App is Done

If you’re looking to build a social-enabled Instagram clone with Uploadcare, check out the video tutorials by HowCode.

pyuploadcare is an official Uploadcare Python library providing wrappers for file uploads, API interactions, and Image Transformations. In this guide, we will stick with using ImageField, a File Uploader implementation for Django.

It should take you about 20 minutes to walk through the steps of this guide and build an image-grid-enabled project with Django and File Uploader.

Before We Begin

Uploadcare Account

In case you don’t have an Uploadcare account, Sign Up for one. Once you get it, navigate to your dashboard to create a new project or discover Public and Secret API keys for an existing one.

Python/Django

Our Python library, pyuploadcare, consists of the Uploadcare API interface and a couple of Django goodies. Although it isn’t necessary to go with Django, we will use it to build a sample project.

You should either have Python of version 2.7 or one of the latest 3.x and one of the latest versions of Django. Take a look at our compatibility list for detailed info.

We won’t describe the Python installation, as it may depend on your OS. Feel free to google the guide suitable for you.

It’s a good practice to always use a per-project virtualenv when developing locally with Python. It is also a good way to get around the Python versions ambiguity. Generally, you create and activate a virtual environment this way:

pip install --upgrade virtualenv
cd instagrid # your project directory

# For Linux/MacOS
virtualenv --python python3 instagrid
source instagrid/bin/activate

# For Windows
virtualenv --python "c:\python36\python.exe" instagrid
.\instagrid\Scripts\activate

If the commands worked out, your CLI prompt should change like this:

(instagrid) HostName:WorkingDirectory UserName$

Now you can install Django and pyuploadcare:

pip install django
pip install pyuploadcare

Step 1. Set Up Your Django Project

In the first step, we will be setting up your new project with the correct config and files.

Create New Project

Let’s start with creating the project:

django-admin startproject instagrid
cd instagrid
python manage.py runserver

After running these three commands, open http://127.0.0.1:8000 in your browser. You should already see the Django welcome screen:

Django Welcome Screen

Now stop the server using Ctrl+C and run default Django migrations, which Django asks to apply every time you run the server:

python manage.py migrate

Tweak the Config

Open the /instagrid/settings.py file and find the INSTALLED_APPS section. There, add lines for your app name and pyuploadcare:

INSTALLED_APPS = [
    'instagrid',
    'pyuploadcare.dj',
    ...
]

This, among other things, allows Django to look for models.py in your app’s directory.

Also, in the same file, find the definition of DIRS in the TEMPLATES section. Here we will add the path to the templates directory:

TEMPLATES = [
    {
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        ...
    },
]

The last thing related to this file is your Uploadcare config. Put the API Keys you discovered earlier in this guide somewhere in the file like another settings variable:

UPLOADCARE = {
    'pub_key': 'YOUR_PUBLIC_KEY',
    'secret': 'YOUT_PRIVATE_KEY',
}

WSGI_APPLICATION = ...

Create a Model

Say, we would like to store the info about uploaded images in a database. Create a new file under /instagrid/ named models.py. Here’s the sample model we will put there:

from django.db import models
from pyuploadcare.dj.models import ImageField


class Post(models.Model):
    photo = ImageField(blank=True, manual_crop="")

ImageField is the pyuploadcare implementation of our File Uploader, which you can use as a regular Django’s TextField.

Make and apply our app migrations to create a DB structure for the new model:

python manage.py makemigrations instagrid
python manage.py migrate

Step 2. Create a Template and a View

Now that we have done the groundwork for the app let’s make the app’s main page. It will serve as an image gallery and a place for the “Upload” button too.

We will not describe the process of building an HTML page. More tips on it you can easily find across the web.

Create the templates folder under your project’s main directory (it’s near the manage.py), and put your index.html file there.

Open index.html in your text editor, and note the following. The form.media here is a default Django form property which is going to render any scripts needed for the form to work, in our case – Uploadcare scripts:

<head>
  <title>Instagrid</title>
  {{ form.media }}
</head>

The following is the Django way of displaying forms:

<form action="" method="post">
  {% csrf_token %}
  {{ form }}
  <input type="submit" value="Save"/>
</form>

And here is the part that renders uploaded images, which data are stored in DB. We’re using some capabilities of our Image Transformations to crop an image and define its quality:

{% if posts %}
{% for post in posts %}
<div class="col-md-4">
  <img class="img-fluid" src="{{ post.photo.cdn_url }}-/crop/600x600/center/-/quality/lightest/" alt=""></div>
{% endfor %}
{% endif %}

The last thing in this step is creating a view. Views help Django know what template should be displayed and what data should be passed there.

Create a new file named views.py under the /instagrid/ directory in your app. Put there the following code:

from django.shortcuts import render, redirect
from .models import Post
from .forms import PostForm

def home(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.save()
    else:
        form = PostForm()

    try:
        posts = Post.objects.all()
    except Post.DoesNotExist:
        posts = None

    return render(request, 'index.html', { 'posts': posts, 'form': form })

This code is just slightly different from any basic tutorial’s one. Here we define the home view, which saves the form data on POST request and passes all the objects stored in Post DB.

To make view show up on the site, you have to also change the /instagrid/urls.py like that:

from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.home)
]

Step 3. Create a Form

We created a Post model in the first step and an index.html template together with the home view in the second. To make them work together, we need to implement the last component in our sample app – a form.

First, create the forms.py file under the /instagrid/ directory in your project.

The simplest way is to create a form from a model. Insert the following snippet into the newly created file:

from django import forms
from .models import Post
from pyuploadcare.dj.forms import ImageField

class PostForm(forms.ModelForm):
    photo = ImageField(label='')
  
    class Meta:
        model = Post
        fields = ('photo',)

You can read more about how these are built in Django Docs. One thing to note is the following line:

photo = ImageField(label='')

We set the label to an empty string to ensure that we won’t have labels in our form. Feel free to drop this argument if you like them 👍

Save all the edited files and run the server:

python manage.py runserver

Now open http://127.0.0.1:8000 in your browser and play around with your Instagrid application ✨

The App is Done

Conclusion

You’ve just built a Django app with Instagram-like grid feed and image uploading by Uploadcare 📷

There’s more to it: you can handle API requests and Image Transformations, and enable the In-Browser Image Editing feature with pyuploadcare too. To continue your way with Uploadcare, take a look at these links:

In case you have any questions, feel free to post those around our community area.

We’re always happy to help with code, integration, and other stuff. Search our site for more info or post your question in our Community Area.