Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - how do you turn an InMemoryUploadedFile into an ImageField's FieldFile?

I've been trying help(django.db.models.ImageField) and dir(django.db.models.ImageField), looking for how you might create a ImageField object from an image that is uploaded.

request.FILES has the images as InMemoryUploadedFile, but I'm trying to save a model that contains an ImageField, so how do I turn the InMemoryUploadedFile into the ImageField?

How do you go about finding this type of thing out? I suspect that the two classes have an inheritance relationship, but I'd have to do lots of dir() -ing to find out if I were to look.

like image 615
Louis Sayers Avatar asked Feb 03 '09 02:02

Louis Sayers


2 Answers

You need to save the InMemoryUploadedFile to the ImageField rather than 'turning' it into an ImageField:

image = request.FILES['img']
foo.imagefield.save(image.name, image)

where foo is the model instance, and imagefield is the ImageField.

Alternatively, if you are pulling the image out of a form:

image = form.cleaned_data.get('img')
foo.imagefield.save(image.name, image)
like image 60
BenLoft Avatar answered Sep 28 '22 05:09

BenLoft


You trying to do it in ModelForm?

This is how i did for file field

class UploadSongForm(forms.ModelForm):
    class Meta:
        model = Mp3File

    def save(self):
        content_type = self.cleaned_data['file'].content_type
        filename = gen_md5() + ".mp3"
        self.cleaned_data['file'] = SimpleUploadedFile(filename, self.cleaned_data['file'].read(), content_type)
        return super(UploadSongForm, self).save()

You can take it as example and look in source what InMemoryUploadedFile class needs in initialization parameters.

like image 28
user20955 Avatar answered Sep 28 '22 05:09

user20955