Simple Image or File upload with django

28 February, 2016
Python Django

Image or file upload in django.

It could get quite painful to setup a simple a django model file upload field

Altough it is trivial and involves simple setup with few steps. This is a simple snippet to make an image upload to your model in django. Assuming you are setting this up for model ImageField. There is also a dependency to python image library Pillow. Install via pip install Pillow
from django.db import models

class DummyModel(models.Model):
    name = models.CharField(max_length=256)
    image = models.ImageField(upload_to="path/", default = 'path/none/no-img.jpg')
Here i have setup a simple a model image field on django model with models.ImageField. The upload_to parameter that you see here, is the path that you want to upload to the final name will be based on the actual file name uploaded.

You also need to add a few configuration to your settings file.

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')

MEDIA_URL tells django what path to prepend when it is creating the path. And media_root is the path where the uploaded files go.

Thank you for taking the time to read this post. If you're considering using Digital Ocean, the hosting provider this blog is hosted on, please consider using this link to sign up.