2014-08-16

Django File Upload

The following is a minimalistic but complete example of handling file upload in Django 1.6.


=== forms.py ===

from django import forms

class UploadFileForm(forms.Form):
    file = forms.FileField()

=== views.py ===

import os.path
from django.http import HttpResponse
from django.shortcuts import render
from .forms import UploadFileForm
          
def home(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            return HttpResponse("Upload Successful.")
    else:
        form = UploadFileForm()
    return render(request, 'home.html', {'form': form})

def handle_uploaded_file(f):
    with open(os.path.join('/path/to/', f.name), 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

=== home.html ===
<html>
<body>

<form action="" method="post" {% if form.is_multipart %}enctype="multipart/form-data"{% endif %}>
  {{ form.as_p }}
  {% csrf_token %}
  <input type="submit" value="Submit" />
</form>

</body>
</html>

No comments: