Mengelola berkasLink to this heading

This document describes Django's file access APIs for files such as those uploaded by a user. The lower level APIs are general enough that you could use them for other purposes. If you want to handle "static files" (JS, CSS, etc.), see Bagaimana mengelola berkas statik (misalnya gambar, JavaScript, CSS).

Secara awalan, Django menyimpan berkas-berkas secara lokal, menggunakan pengaturan MEDIA_ROOT dan MEDIA_URL. Contoh-contoh dibawah menganggap bahwa anda sedang menggunakan awalan-awalan ini.

However, Django provides ways to write custom file storage systems that allow you to completely customize where and how Django stores files. The second half of this document describes how these storage systems work.

Menggunakan berkas dalam modelLink to this heading

Ketika anda menggunakan FileField atau ImageField, Django menyediakan sekumpulan dari API anda dapat gunakan untuk berhbungan dengan berkas itu.

Pertimbangkan model berikut, menggunakan ImageField untuk menyimpan sebuah foto:

Code
from django.db import models


class Car(models.Model):
    name = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    photo = models.ImageField(upload_to="cars")
    specs = models.FileField(upload_to="specs")

Any Car instance will have a photo attribute that you can use to get at the details of the attached photo:

Python console
>>> car = Car.objects.get(name="57 Chevy")
>>> car.photo
<ImageFieldFile: cars/chevy.jpg>
>>> car.photo.name
'cars/chevy.jpg'
>>> car.photo.path
'/media/cars/chevy.jpg'
>>> car.photo.url
'https://media.example.com/cars/chevy.jpg'

Obyek ini -- car.photo dalam contoh -- adalah obyek File, yang berarti itu mempunyai semua metode-metode dan atribut-atribut digambarkan dibawah.

For example, you can change the file name by setting the file's name to a path relative to the file storage's location (MEDIA_ROOT if you are using the default FileSystemStorage):

Python console
>>> import os
>>> from django.conf import settings
>>> initial_path = car.photo.path
>>> car.photo.name = "cars/chevy_ii.jpg"
>>> new_path = settings.MEDIA_ROOT + car.photo.name
>>> # Move the file on the filesystem
>>> os.rename(initial_path, new_path)
>>> car.save()
>>> car.photo.path
'/media/cars/chevy_ii.jpg'
>>> car.photo.path == new_path
True

To save an existing file on disk to a FileField:

Python console
>>> 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()
...

Obyek FileLink to this heading

Di bagian dalam, Django menggunakan sebuah instance django.core.files.File kapanpun itu butuh untuk mewakili sebuah berkas.

Most of the time you'll use a File that Django's given you (i.e. a file attached to a model as above, or perhaps an uploaded file).

If you need to construct a File yourself, the easiest way is to create one using a Python built-in file object:

Python console
>>> from django.core.files import File

# Create a Python file object using open()
>>> f = open("/path/to/hello.world", "w")
>>> myfile = File(f)

Sekarang anda dapat menggunakan atribut-atribut terdokumentasi apapun dan metode-metode dari kelas File.

Be aware that files created in this way are not automatically closed. The following approach may be used to close files automatically:

Python console
>>> from django.core.files import File

# Create a Python file object using open() and the with statement
>>> with open("/path/to/hello.world", "w") as f:
...     myfile = File(f)
...     myfile.write("Hello World")
...
>>> myfile.closed
True
>>> f.closed
True

Closing files is especially important when accessing file fields in a loop over a large number of objects. If files are not manually closed after accessing them, the risk of running out of file descriptors may arise. This may lead to the following error:

Pytb
OSError: [Errno 24] Too many open files

Penyimpanan berkasLink to this heading

Behind the scenes, Django delegates decisions about how and where to store files to a file storage system. This is the object that actually understands things like file systems, opening and reading files, etc.

Django's default file storage is 'django.core.files.storage.FileSystemStorage'. If you don't explicitly provide a storage system in the default key of the STORAGES setting, this is the one that will be used.

Lihat dibawah untuk rincian dari sistem penyimpanan berkas awalan siap-pakai, dan lihat Bagaimana menulis kelas penyimpanan disesuaikan untuk informasi pada menulis sistem penyimpanan berkas anda sendiri.

Obyek penyimpananLink to this heading

Though most of the time you'll want to use a File object (which delegates to the proper storage for that file), you can use file storage systems directly. You can create an instance of some custom file storage class, or -- often more useful -- you can use the global default storage system:

Python console
>>> from django.core.files.base import ContentFile
>>> from django.core.files.storage import default_storage

>>> path = default_storage.save("path/to/file", ContentFile(b"new content"))
>>> path
'path/to/file'

>>> default_storage.size(path)
11
>>> default_storage.open(path).read()
b'new content'

>>> default_storage.delete(path)
>>> default_storage.exists(path)
False

Lihat API penyimpanan berkas untuk API penyimpanan berkas.

Kelas penyimpanan sistem berkas siap-pakaiLink to this heading

Django dibekali dengan kelas django.core.files.storage.FileSystemStorage yang menerapkan penyimpanan berkas sistem berkas lokal.

Sebagai contoh, kode berikut akan menyimpan berkas-berkas terunggah dibawah /media/photos meskipun dari apa pengaturan MEDIA_ROOT:

Code
from django.core.files.storage import FileSystemStorage
from django.db import models

fs = FileSystemStorage(location="/media/photos")


class Car(models.Model):
    ...
    photo = models.ImageField(storage=fs)

Custom storage systems 1 bekerja cara sama: anda dapat melewatkan mereka sebagai argumen storage pada sebuah FileField.

Using a callableLink to this heading

You can use a callable as the storage parameter for FileField or ImageField. This allows you to modify the used storage at runtime, selecting different storages for different environments, for example.

Your callable will be evaluated when your models classes are loaded, and must return an instance of Storage.

Sebagai contoh:

Code
from django.conf import settings
from django.db import models
from .storages import MyLocalStorage, MyRemoteStorage


def select_storage():
    return MyLocalStorage() if settings.DEBUG else MyRemoteStorage()


class MyModel(models.Model):
    my_file = models.FileField(storage=select_storage)

In order to set a storage defined in the STORAGES setting you can use storages:

Code
from django.core.files.storage import storages


def select_storage():
    return storages["mystorage"]


class MyModel(models.Model):
    upload = models.FileField(storage=select_storage)