From fba0149e1604ad4ab3745abff8bba0d38bbfe321 Mon Sep 17 00:00:00 2001 From: Tim Graham Date: Fri, 10 Aug 2012 16:19:20 -0400 Subject: [PATCH] [1.4.X] Fixed #17016 - Added examples for file uploads in views. Thanks Tim Saylor for the draft patch and Aymeric Augustin and Claude Paroz for feedback. Backport of eff6ba2f64 from master --- AUTHORS | 1 + docs/topics/http/file-uploads.txt | 44 +++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/AUTHORS b/AUTHORS index 0af0c7961e..3d4ec52445 100644 --- a/AUTHORS +++ b/AUTHORS @@ -453,6 +453,7 @@ answer newbie questions, and generally made Django that much better: Vinay Sajip Bartolome Sanchez Salado Kadesarin Sanjek + Tim Saylor Massimo Scamarcia Paulo Scardine David Schein diff --git a/docs/topics/http/file-uploads.txt b/docs/topics/http/file-uploads.txt index 1c1ef776bb..8865e23936 100644 --- a/docs/topics/http/file-uploads.txt +++ b/docs/topics/http/file-uploads.txt @@ -179,6 +179,50 @@ Three settings control Django's file upload behavior: Which means "try to upload to memory first, then fall back to temporary files." +Handling uploaded files with a model +------------------------------------ + +If you're saving a file on a :class:`~django.db.models.Model` with a +:class:`~django.db.models.FileField`, using a :class:`~django.forms.ModelForm` +makes this process much easier. The file object will be saved when calling +``form.save()``:: + + from django.http import HttpResponseRedirect + from django.shortcuts import render + from .forms import ModelFormWithFileField + + def upload_file(request): + if request.method == 'POST': + form = ModelFormWithFileField(request.POST, request.FILES) + if form.is_valid(): + # file is saved + form.save() + return HttpResponseRedirect('/success/url/') + else: + form = ModelFormWithFileField() + return render('upload.html', {'form': form}) + +If you are constructing an object manually, you can simply assign the file +object from :attr:`request.FILES ` to the file +field in the model:: + + from django.http import HttpResponseRedirect + from django.shortcuts import render + from .forms import UploadFileForm + from .models import ModelWithFileField + + def upload_file(request): + if request.method == 'POST': + form = UploadFileForm(request.POST, request.FILES) + if form.is_valid(): + instance = ModelWithFileField(file_field=request.FILES['file']) + instance.save() + return HttpResponseRedirect('/success/url/') + else: + form = UploadFileForm() + return render('upload.html', {'form': form}) + + ``UploadedFile`` objects ========================