1

I have a question similar to this: how to manually assign imagefield in Django

Except my file is coming from a remote host and I am only given an url, so something like:

class Book(models.Model):
    name = models.CharField()
    url = models.URLField()
    file = models.FileField(null=True, blank=True, editable=False)

class BookForm(forms.ModelForm):
    class Meta:
        model = Book

def view(request):
    if request.POST:
        form = BookForm()
        if form.is_valid():
            request = form.instance.source_url
            try:
                f = urlopen(request)
                # ...create open file obj...
                form.instance.local_file.save(form.instance.ref, f.read(), True)

            except Exception:
                print 3

How should I turn f into an open file object in this case so I can save its contents?

Community
  • 1
  • 1
Hedde van der Heide
  • 21,841
  • 13
  • 71
  • 100

1 Answers1

4

Using requests it is trivial.

import requests
from StringIO import StringIO

r = requests.get(file_url)
f = StringIO(r.content)

# f.read()

Finally, as written - your code will lead to problems as you are reassigning request, which is passed in. You should change this line request = form.instance.source_url to something else like file_url = from.instance.source_url.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284