Upload file from URL in Django

Short snippet: how to upload file/image from URL or locale file system in Django.

Suppose we have a model like this:

from django.db import models

class Animal(models.Model):
    name = models.CharField(u'name', max_length=255)
    photo =  ImageField(upload_to='photos')

Uploading

import os
import urllib
from django.core.files import File

image = urllib.urlretrieve(url)
animal = Animal.objects.create(name='Dog')
fname = os.path.basename(url)

with open(image[0]) as fp:
    animal.photo.save(fname, File(fp))
    animal.save()
comments powered by Disqus