开发者

Django file uploads - Just can't work it out

开发者 https://www.devze.com 2022-12-26 13:41 出处:网络
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

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(reque开发者_StackOverflowst.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!


This is the way i do it:

def handle_uploaded_file(f, instance):
    instance.field.save('name_slug.ext', f, True)
    instance.save()


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

Or I miss something?

0

精彩评论

暂无评论...
验证码 换一张
取 消