0

I'm trying to submit image from url based on the answers of this question but as a result I have image file stored successfully , but with filename .jpg instead of image-name.jpg

code

import urllib2
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile

from myapp.models import Mymodel
# Mymodel contain ImageField named image

extract_url = 'http://example.com/image-name.jpg'
my_temp = Mymodel()

image_name = extract_url.split('/')[-1]

image_temp = NamedTemporaryFile(delete=True)
image_temp.write(urllib2.urlopen(extract_url).read())
image_temp.flush()

my_temp.image.save(image_name, File(image_temp), save=True)

I did not overwrite Mymodel save method and image_name value is image-name.jpg

>> print image_name
u'image-name.jpg'

EDIT : Include Mymodel code

def _image_container(instance, filename):
    return os.path.join(settings.IMAGE_FILES_ROOT, instance.slug + '.' + filename.split('.')[-1].lower())

class Mymodel(models.Model):
    ...
    slug = AutoSlugField(_('Slug'), unique=True, populate_from='title', editable=True)
    image = thumbnail.ImageField(_('Image'), upload_to=_image_container)

I want to keep _image_container functionality because it works nice on manual upload

Community
  • 1
  • 1
Goran
  • 6,644
  • 11
  • 34
  • 54

1 Answers1

0

Your upload_to _image_container function renames the image based on the Mymodel instance's slug, but the model instance you use for saving your image has no slug, so obviously you have exactly what you asked for... To make a long story short you have to explicitely set the slug attribute of your temporary Mymodel instance to whatever name you want for the image.

import os
extract_url = 'http://example.com/image-name.jpg'
image_name = extract_url.split('/')[-1]
slug = os.path.splitext(image_name)[0]
my_temp = Mymodel(slug=slug)

# etc
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118