Django file uploads - Just can't work it out

Posted by phoebebright on Stack Overflow See other posts from Stack Overflow or by phoebebright
Published on 2010-04-13T20:16:54Z Indexed on 2010/04/13 23:13 UTC
Read the original article Hit count: 338

Filed under:
|
|

OK I give up - after 5 solid hours trying to get a django form to upload a file, I've checked out all the links in stackoverflow and googled and googled. Why is it so hard, I just want it to work like the admin file upload?

So I get that I need code like:

            if submitForm.is_valid():
                  handle_uploaded_file(request.FILES['attachment'])
                  obj = submitForm.save()

and I can see my file in request.FILES['attachment'] (yes I have enctype set) but what am I supposed to do in handle_uploaded_file? The examples all have a fixed file name but obviously I want to upload the file to the directory I defined in the model, but I can't see where I can find that.

def handle_uploaded_file(f):
  destination = open('fyi.xml', 'wb+')
  for chunk in f.chunks():
    destination.write(chunk)
  destination.close()

Bet I'm going to feel really stupid when someone points out the obvious!

© Stack Overflow or respective owner

Related posts about django-forms

Related posts about django