Django files

Django files

Django files — A file attached to a model as above, or perhaps an uploaded file.

>>> car = Car.objects.get(name="57 Chevy")
<ImageFieldFile: cars/chevy.jpg>

The file is saved as part of saving the model in the database, so the actual file name used on disk cannot be relied on until after the model has been saved.

File Uploads

def handle_uploaded_file(f):
    with open('some/file/name.txt', 'wb+') as destination:
        for chunk in f.chunks():
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import UploadFileForm

# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            return HttpResponseRedirect('/success/url/')
        form = UploadFileForm()
    return render(request, 'upload.html', {'form': form})

When Django handles a file upload, the file data ends up placed in request.FILES (for more on the request object see the documentation for request and response objects).

Django files — Structure map

Clickable & Draggable!

Django files — Related pages: