views:

162

answers:

2

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!

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

Or I miss something?

Anatoly Rr
Where do I get the 'upload_to' that I put in the model? Or do I need to have a path defined in the function instead?
+1  A: 

This is the way i do it:

def handle_uploaded_file(f, instance):
    instance.field.save('name_slug.ext', f, True)
    instance.save()
diegueus9
Simple and works perfectly. Many thanks.
Just for clarity, this is my save line for a field called 'attachment1' and the instance is comm.comm.attachment1.save(request.FILES['attachment1']._name, request.FILES['attachment1'], True)
What is the second parameter to handle_uploaded_file? This answer only confuses me more.
amarillion