---
title: "Mengelola berkas"
version: 2.0
locale: id
source: https://docs.djangoproject.com/id/2.0/topics/files/
canonical: https://djangodocs.dev/id/2.0/topics/files/
---
# Mengelola berkas

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 [Mengelola berkas statis (sebagai contoh gambar, JavaScript, CSS)](/id/2.0/howto/static-files/).

Secara awalan, Django menyimpan berkas-berkas secara lokal, menggunakan pengaturan [`MEDIA_ROOT`](/id/2.0/ref/settings/#std-setting-MEDIA_ROOT) dan [`MEDIA_URL`](/id/2.0/ref/settings/#std-setting-MEDIA_URL). Contoh-contoh dibawah menganggap bahwa anda sedang menggunakan awalan-awalan ini.

However, Django provides ways to write custom [file storage systems](#file-storage) 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 model

Ketika anda menggunakan [`FileField`](/id/2.0/ref/models/fields/#django.db.models.FileField) atau [`ImageField`](/id/2.0/ref/models/fields/#django.db.models.ImageField), Django menyediakan sekumpulan dari API anda dapat gunakan untuk berhbungan dengan berkas itu.

Pertimbangkan model berikut, menggunakan [`ImageField`](/id/2.0/ref/models/fields/#django.db.models.ImageField) untuk menyimpan sebuah foto:

```
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')
```

Instance `Car` apapun akan mempunyai atribut `photo` yang anda dapat gunakan untuk mendapatkan rincian dari foto terlampir:

```
>>> car = Car.objects.get(name="57 Chevy")
>>> car.photo
<ImageFieldFile: chevy.jpg>
>>> car.photo.name
'cars/chevy.jpg'
>>> car.photo.path
'/media/cars/chevy.jpg'
>>> car.photo.url
'http://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.

> **Note**
>
> Berkas disimpan sebagai bagian dari menyimpan model dalam basisdata, jadi nama berkas sebenarnya digunakan pada cakram tidak dapat bergantung setelah model disimpan.

Sebagai contoh, anda dapat merubah nama berkas dengan mengatur [`name`](/id/2.0/ref/files/file/#django.core.files.File.name) berkas ke jalur relatif ke tempat penyimpanan berkas ([`MEDIA_ROOT`](/id/2.0/ref/settings/#std-setting-MEDIA_ROOT) jika anda sedang menggunakan awalan [`FileSystemStorage`](/id/2.0/ref/files/storage/#django.core.files.storage.FileSystemStorage)):

```
>>> 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
```

## Obyek `File`

Di bagian dalam, Django menggunakan sebuah instance [`django.core.files.File`](/id/2.0/ref/files/file/#django.core.files.File) kapanpun itu butuh untuk mewakili sebuah berkas.

Kebanyakan waktu anda akan cukup menggunakan sebuah `File` yang Django berikan ke anda (yaitu dilampirkan pada model seperti diatas, atau mungkin sebuah berkas terunggah).

Jika anda butuh membangun sebuah `File` anda sendiri, cara termudah adalah membuat satu menggunakan Python obyek `file` siap-pakai:

```
>>> 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`](/id/2.0/ref/files/file/#django.core.files.File).

Waspada bahwa berkas-berkas yang dibuat dalam cara ini tidak otomatis ditutup. Pendekatan berikut mungkin digunakan untuk menutup berkas-berkas otomatis:

```
>>> 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:

```
IOError: [Errno 24] Too many open files
```

## Penyimpanan berkas

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 given by the [`DEFAULT_FILE_STORAGE`](/id/2.0/ref/settings/#std-setting-DEFAULT_FILE_STORAGE)
setting; if you don't explicitly provide a storage system, this is the one that
will be used.

Lihat dibawah untuk rincian dari sistem penyimpanan berkas awalan siap-pakai, dan lihat [Menulis sistem penyimpanan disesuaikan](/id/2.0/howto/custom-file-storage/) untuk informasi pada menulis sistem penyimpanan berkas anda sendiri.

### Obyek penyimpanan

Meskipun kebanyakan waktu anda akan ingin menggunakan sebuah obyek `File` (yang menunjukkan ke penyimpanan sesuai untuk berkas itu), anda dapat menggunakan sistem penyimpanan berkas langsung. Anda dapat membuat sebuah instance dari beberapa kelas penyimpanan berkas penyesuaian, atau -- sering lebih berguna -- anda dapat menggunakan sistem penyimpanan awalan global:

```
>>> from django.core.files.base import ContentFile
>>> from django.core.files.storage import default_storage

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

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

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

Lihat [File storage API](/id/2.0/ref/files/storage/) untuk API penyimpanan berkas.

### Kelas penyimpanan sistem berkas siap-pakai

Django dibekali dengan kelas [`django.core.files.storage.FileSystemStorage`](/id/2.0/ref/files/storage/#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`](/id/2.0/ref/settings/#std-setting-MEDIA_ROOT):

```
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`](/id/2.0/ref/models/fields/#django.db.models.FileField).
