File upload with django

By : Hulk
Source: Stackoverflow.com
Question!

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>
By : Hulk


Answers

You need to set enctype attribute on your form:

By : cji


This video can help you solving your question :)
By: admin