views:

61

answers:

1

What is wrong with the following code for file uploading.The request.FILES['file'] looks empty

Models:

  from django.db import models 
  from django import forms

  class UploadFileForm(forms.Form):
      title = forms.CharField(max_length=50)
      file  = forms.FileField(label="Your file")

Views:

def index(request):
  if request.method == 'POST':
   a=request.POST
   logging.debug(a["title"])
   logging.debug(a["file"])
   form = UploadFileForm()
   form = UploadFileForm(request.POST, request.FILES)

  handle_uploaded_file(request.FILES['file'])

  if form.is_valid():
     handle_uploaded_file(request.FILES['file'])

     return HttpResponseRedirect('/Files/')
else:
  form = UploadFileForm()
return render_to_response('Files/index.html', {'form': form})


def handle_uploaded_file(f):
 logging.debug("here1")
 #destination = open('some/file/name.txt', 'wb+')
 destination = open('/tmp', 'wb+')
 for chunk in f.chunks():
   destination.write(chunk)
 destination.close()

Templates:

      <form name="lang" action="/test/" method="post">
      <table>
     <tr><td>
     <b> {{ form.file.label_tag }}</b>  {{ form.file}}
     </td></tr>
     <tr><td>
     <input type="hidden" value="title" name="title" id="title" />
     <input type="submit" value="Save" id="Save"/>
     </td></tr>
     </table>
    </form>
+5  A: 

You need to set enctype attribute on your form:

<form enctype="multipart/form-data" method="post" action="/foo/">

Like they say in the docs.

cji
Shaks, I missed that part..Thanks it worked
Hulk
@Hulk, if it worked, please mark this answered as accepted!
Dominic Rodger