summaryrefslogtreecommitdiff
path: root/docs/topics
diff options
context:
space:
mode:
authorTim Graham <timograham@gmail.com>2012-08-10 16:19:20 -0400
committerTim Graham <timograham@gmail.com>2012-08-10 16:19:20 -0400
commiteff6ba2f64ea5426502daadb04fbe1e85ace068a (patch)
tree2107ec61718f971fc4750c8c7f86b8aab8e776bb /docs/topics
parent92b2dec918d7b73456899ecb5726cc03b86bd068 (diff)
Fixed #17016 - Added examples for file uploads in views.
Thanks Tim Saylor for the draft patch and Aymeric Augustin and Claude Paroz for feedback.
Diffstat (limited to 'docs/topics')
-rw-r--r--docs/topics/http/file-uploads.txt44
1 files changed, 44 insertions, 0 deletions
diff --git a/docs/topics/http/file-uploads.txt b/docs/topics/http/file-uploads.txt
index 877d3b4100..0b0ef3b193 100644
--- a/docs/topics/http/file-uploads.txt
+++ b/docs/topics/http/file-uploads.txt
@@ -178,6 +178,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 <django.http.HttpRequest.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
========================