diff --git a/docs/topics/files.txt b/docs/topics/files.txt index 9398df41d7..f6fd82ec9a 100644 --- a/docs/topics/files.txt +++ b/docs/topics/files.txt @@ -33,6 +33,7 @@ store a photo:: name = models.CharField(max_length=255) price = models.DecimalField(max_digits=5, decimal_places=2) photo = models.ImageField(upload_to='cars') + specs = models.FileFile(upload_to='specs') Any ``Car`` instance will have a ``photo`` attribute that you can use to get at the details of the attached photo:: @@ -73,6 +74,16 @@ location (:setting:`MEDIA_ROOT` if you are using the default >>> car.photo.path == new_path True +To save an existing file on disk to a :class:`~django.db.models.FileField`:: + + >>> from pathlib import Path + >>> from django.core.files import File + >>> path = Path('/some/external/specs.pdf') + >>> car = Car.objects.get(name='57 Chevy') + >>> with path.open(mode='rb') as f: + ... car.specs = File(f, name=path.name) + ... car.save() + .. note:: While :class:`~django.db.models.ImageField` non-image data attributes, such diff --git a/docs/topics/http/file-uploads.txt b/docs/topics/http/file-uploads.txt index c946662bba..a46caefed9 100644 --- a/docs/topics/http/file-uploads.txt +++ b/docs/topics/http/file-uploads.txt @@ -126,6 +126,19 @@ model:: form = UploadFileForm() return render(request, 'upload.html', {'form': form}) +If you are constructing an object manually outside of a request, you can assign +a :class:`~django.core.files.File` like object to the +:class:`~django.db.models.FileField`:: + + from django.core.management.base import BaseCommand + from django.core.files.base import ContentFile + + class MyCommand(BaseCommand): + def handle(self, *args, **options): + content_file = ContentFile(b'Hello world!', name='hello-world.txt') + instance = ModelWithFileField(file_field=content_file) + instance.save() + Uploading multiple files ------------------------