| | 181 | Handling uploaded files with a model |
| | 182 | ------------------------------------ |
| | 183 | |
| | 184 | If you're saving a file on a :class:`~django.db.models.Model` with a |
| | 185 | :class:`~django.db.models.FileField`, using a :class:`~django.forms.ModelForm` |
| | 186 | makes this process much easier. The file object will be saved when calling |
| | 187 | ``form.save()``:: |
| | 188 | |
| | 189 | from django.http import HttpResponseRedirect |
| | 190 | from django.shortcuts import render_to_response |
| | 191 | from forms import ModelFormWithFileField |
| | 192 | |
| | 193 | def upload_file(request): |
| | 194 | if request.method == 'POST': |
| | 195 | form = ModelFormWithFileField(request.POST, request.FILES) |
| | 196 | if form.is_valid(): |
| | 197 | # file is saved |
| | 198 | form.save() |
| | 199 | return HttpResponseRedirect('/success/url/') |
| | 200 | else: |
| | 201 | form = ModelFormWithFileField() |
| | 202 | return render_to_response('upload.html', {'form': form}) |
| | 203 | |
| | 204 | If you are constructing an object manually, you can simply assign the file |
| | 205 | object from :attr:`request.FILES <django.http.HttpRequest.FILES>` to the file |
| | 206 | field in the model:: |
| | 207 | |
| | 208 | from django.http import HttpResponseRedirect |
| | 209 | from django.shortcuts import render_to_response |
| | 210 | from models import ModelWithFileField |
| | 211 | |
| | 212 | def upload_file(request): |
| | 213 | if request.method == 'POST': |
| | 214 | form = UploadFileForm(request.POST, request.FILES) |
| | 215 | if form.is_valid(): |
| | 216 | instance = ModelWithFileField(file_field=request.FILES['file']) |
| | 217 | instance.save() |
| | 218 | return HttpResponseRedirect('/success/url/') |
| | 219 | else: |
| | 220 | form = UploadFileForm() |
| | 221 | return render_to_response('upload.html', {'form': form}) |
| | 222 | |
| | 223 | |