On Tue, Nov 16, 2010 at 3:28 AM, Tom Evans <tevans...@googlemail.com> wrote:
> Django doesn't want a python file or text for a django file field, it > wants a django.core.files.File. I find the easiest one to use is the > InMemoryUploadedFile. Here is a snippet I use for fetching an image > from the web, and creating a django.core.files.File object that can be > assigned to a FileField or ImageField on a model: > > h = httplib2.Http() > req, content = h.request(uri) > if req['status'] != '200': > print u'Failed to fetch image from %s' % uri > return None > > import cStringIO > from django.core.files.uploadedfile import InMemoryUploadedFile > out = cStringIO.StringIO() > out.write(content) > return InMemoryUploadedFile( > file=out, > field_name=field, > name=name, > content_type=req['content-type'], > size=out.tell(), > charset=None) > > field should be the name of the field on the model, name should be the > file name of the resource. > > There may be neater ways of doing this, but this keeps it in memory > until django saves it to the upload_to location specified on the > model, and avoids writing it to disk only for django to write it to > disk again. > > Cheers > > Tom > Awesome that worked perfectly! Thanks Tom! -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.