summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJoshua Massover <joshm@simplebet.io>2022-01-26 15:05:33 +0100
committerMariusz Felisiak <felisiak.mariusz@gmail.com>2022-02-03 09:23:02 +0100
commitc9d6e3595cfd0aa58cde1656bd735ecfcd7a872b (patch)
tree303a984b80ffcb3c9c4dff08fb262002d64be9ac
parente459b0f5a0b2bfbc2ac45b3e7f21047ec9e4f345 (diff)
Fixed #32243 -- Added docs examples for manually saving Files.
-rw-r--r--docs/topics/files.txt11
-rw-r--r--docs/topics/http/file-uploads.txt13
2 files changed, 24 insertions, 0 deletions
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
------------------------