mirror of
https://github.com/django/django.git
synced 2024-12-22 17:16:24 +00:00
Fixed #32243 -- Added docs examples for manually saving Files.
This commit is contained in:
parent
e459b0f5a0
commit
c9d6e3595c
@ -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
|
||||
|
@ -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
|
||||
------------------------
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user