models.FileField and InMemoryUploadedFile

1,559 views
Skip to first unread message

rtelep

unread,
Dec 11, 2008, 1:35:19 PM12/11/08
to Django users
I have a model Foo with an ImageField. I want to create new Foo
object from request.FILES and POST from inside a view function.

Ordinarily I would bind a form to request.FILES and request.POST to
get that data:

form = FooForm(request.FILES, request.POST)

But I cannot do that in this case (circumstances.)

I can do "manually" like this:

foo = Foo(
bar = request.POST.get('bar')
)

But not in the case of request.FILES

request.FILES['img'] is an InMemoryUploadedFile object:

<InMemoryUploadedFile: yanks.jpg (image/jpeg)>

How can I feed that to my model's ImageField?

I guess that what I'm basically asking is how can a person do:

>>>from mysite.myapp.models import Foo
>>>foo = Foo(bar = 'baz', img = <what?>)
>>>foo.save()


Rajesh Dhawan

unread,
Dec 11, 2008, 2:22:14 PM12/11/08
to Django users
foo = Foo(bar='baz')
file_content = request.FILES['img']
foo.img.save(file_content.name, file_content, save=True)

For more, see: http://docs.djangoproject.com/en/dev//ref/files/file/

-Rajesh D
Reply all
Reply to author
Forward
0 new messages