| | 182 | Handling uploaded files with a model |
| | 183 | ------------------------------------ |
| | 184 | |
| | 185 | If you're saving a file from a standard form into a :class:`FileField` on a |
| | 186 | model, the process is much easier. The :class:`FileField` accepts the parameter |
| | 187 | 'upload_to', which tells the model where to store your file. In the view, you |
| | 188 | can simply assign the file object from reqeust.FILES to the file field in the |
| | 189 | model and the file will be saved to disk in the location specified by the |
| | 190 | 'upload_to' parameter:: |
| | 191 | |
| | 192 | from django.http import HttpResponseRedirect |
| | 193 | from django.shortcuts import render_to_response |
| | 194 | from models import ModelWithFileField |
| | 195 | |
| | 196 | def upload_file(request): |
| | 197 | if request.method == 'POST': |
| | 198 | form = UploadFileForm(request.POST, request.FILES) |
| | 199 | if form.is_valid(): |
| | 200 | instance = ModelWithFileField(file_field=request.FILES['file']) |
| | 201 | instance.save() |
| | 202 | return HttpResponseRedirect('/success/url/') |
| | 203 | else: |
| | 204 | form = UploadFileForm() |
| | 205 | return render_to_response('upload.html', {'form': form}) |
| | 206 | |