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():
            return HttpResponse("Upload Successful.")
        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():

=== home.html ===

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


No comments: