---
title: "Gaya pengkodean"
version: 4.2
locale: id
source: https://docs.djangoproject.com/id/4.2/internals/contributing/writing-code/coding-style/
canonical: https://djangodocs.dev/id/4.2/internals/contributing/writing-code/coding-style/
---
# Gaya pengkodean

Silahkan ikuti standar pengkodean ini ketika menulis kode untuk penyertaan di Django.

## Pemeriksaan pra-komitmen

[pre-commit](https://pre-commit.com) is a framework for managing pre-commit
hooks. These hooks help to identify simple issues before committing code for
review. By checking for these issues before code review it allows the reviewer
to focus on the change itself, and it can also help to reduce the number of CI
runs.

Untuk menggunakan alat, pertama pasang `pre-commit` dan kemudian kait git:

```console
$ python -m pip install pre-commit
$ pre-commit install
```

*Windows*

```doscon
...\> py -m pip install pre-commit
...\> pre-commit install
```

On the first commit `pre-commit` will install the hooks, these are
installed in their own environments and will take a short while to
install on the first run. Subsequent checks will be significantly faster.
If an error is found an appropriate error message will be displayed.
If the error was with `black` or `isort` then the tool will go ahead and
fix them for you. Review the changes and re-stage for commit if you are happy
with them.

## Gaya Phyton

- All files should be formatted using the [black](https://black.readthedocs.io/en/stable/) auto-formatter. This will be
  run by `pre-commit` if that is configured.
- The project repository includes an `.editorconfig` file. We recommend using
  a text editor with [EditorConfig](https://editorconfig.org/) support to avoid indentation and
  whitespace issues. The Python files use 4 spaces for indentation and the HTML
  files use 2 spaces.
- Meskipun sebaliknya ditentukan, ikuti [**PEP 8**](https://peps.python.org/pep-0008/).

  Use [flake8](https://pypi.org/project/flake8/) to check for problems in this area. Note that our
  `.flake8` file contains some excluded files (deprecated modules we don't
  care about cleaning up and some third-party code that Django vendors) as well
  as some excluded errors that we don't consider as gross violations. Remember
  that [**PEP 8**](https://peps.python.org/pep-0008/) is only a guide, so respect the style of the surrounding code
  as a primary goal.

  An exception to [**PEP 8**](https://peps.python.org/pep-0008/) is our rules on line lengths. Don't limit lines of
  code to 79 characters if it means the code looks significantly uglier or is
  harder to read. We allow up to 88 characters as this is the line length used
  by `black`. This check is included when you run `flake8`. Documentation,
  comments, and docstrings should be wrapped at 79 characters, even though
  [**PEP 8**](https://peps.python.org/pep-0008/) suggests 72.
- String variable interpolation may use
  [%-formatting](https://docs.python.org/3/library/stdtypes.html#old-string-formatting), [f-strings](https://docs.python.org/3/reference/lexical_analysis.html#f-strings), or [`str.format()`](https://docs.python.org/3/library/stdtypes.html#str.format) as appropriate, with the goal of
  maximizing code readability.

  Final judgments of readability are left to the Merger's discretion. As a
  guide, f-strings should use only plain variable and property access, with
  prior local variable assignment for more complex cases:

  ```
  # Allowed
  f"hello {user}"
  f"hello {user.name}"
  f"hello {self.user.name}"

  # Disallowed
  f"hello {get_user()}"
  f"you are {user.age * 365.25} days old"

  # Allowed with local variable assignment
  user = get_user()
  f"hello {user}"
  user_days_old = user.age * 365.25
  f"you are {user_days_old} days old"
  ```

  f-strings should not be used for any string that may require translation,
  including error and logging messages. In general `format()` is more
  verbose, so the other formatting methods are preferred.

  Don't waste time doing unrelated refactoring of existing code to adjust the
  formatting method.
- Hindari penggunaan "we" dalam komentar, sebagai contoh "Loop over" daripada "We loop over".
- Gunakan garis bawah, bukan camelCase, untuk variabel, fungsi dan nama-nama metode (yaitu `poll.get_unique_voters()`, bukan `poll.getUniqueVoters()`).
- Gunakan `InitialCaps` untuk nama-nama kelas (atau untuk fungsi pabrik yang mengembalikan kelas-kelas).
- Dalam docstring, ikuti gaya dari docstring yang ada dan [**PEP 257**](https://peps.python.org/pep-0257/).
- Dalam percobaan, gunakan [`assertRaisesMessage()`](/id/4.2/topics/testing/tools/#django.test.SimpleTestCase.assertRaisesMessage) dan [`assertWarnsMessage()`](/id/4.2/topics/testing/tools/#django.test.SimpleTestCase.assertWarnsMessage) daripada [`assertRaises()`](https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises) dan [`assertWarns()`](https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertWarns) sehingga anda dapat memeriksa pengecualian atau pesan peringatan. Hanya gunakan [`assertRaisesRegex()`](https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaisesRegex) dan [`assertWarnsRegex()`](https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertWarnsRegex) jika anda butuh pencocokan regular expression.

  Gunakan [`assertIs(…, True/False)`](https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertIs) untuk pengujian nilai boolean, daripada [`assertTrue()`](https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertTrue) dan [`assertFalse()`](https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertFalse), sehingga anda dapat memeriksa nilai boolean sebenarnya, bukan kebenaran dari pernyataan.
- Dalam docstring percobaan, nyatakan perilaku yang diharapkan yang setiap percobaan ditunjukkan. Jangan menyertakan pembukaan seperti "Tests that" atau "Ensures that".

  Acuan tiket balikan untuk mengaburkan masalah dimana tiket mempunyai rincian tambahan yang tidak dapat dengan mudah digambarkan dalam docstring atau komentar. Termasuk nomor tiket pada akhir dari sebuah kalimat seperti ini:

  ```
  def test_foo():
      """
      A test docstring looks like this (#123456).
      """
      ...
  ```

## Impor

- Gunakan [isort](https://github.com/PyCQA/isort#readme) utnuk otomatis pengurutan impor menggunakan panduan dibawah.

  Mulai cepat:

  ```console
  $ python -m pip install "isort >= 5.1.0"
  $ isort .
  ```

  *Windows*

  ```doscon
  ...\> py -m pip install "isort >= 5.1.0"
  ...\> isort .
  ```

  Ini menjalankan `isort` secara berulang dari pelipat anda saat ini, merubah berkas apapun yang tidak sesuai pada baris panduan. Jika anda butuh mengimpor rusak (untuk menghidari impor memutar, sebagai contoh) gunakan komentar seperti ini:

  ```
  import module  # isort:skip
  ```
- Taruh impor dalam kelompok ini: akan datang, pustaka standar, pustaka pihak-ketiga, komponen Django lainnya, komponen Django lokal, coba/pengecualian. Urutkan baris dalam setiap kelompok secara alfabet dengan nama modul penuh. Tempatkan semua pernyataan `import module` sebelum `from module import objects` di setiap bagian. Gunakan impor sepenuhnya untuk komponen Django lainnya dan impor berhubugan untuk komponen lokal.
- Pada setiap baris, mengabjadkan barang dengan barang huruf besar dikelompokkan sebelum barang huruf kecil.
- Putuskan baris panjang menggunakan kurung dan lekukan garis kelanjutan dengan 4 ruang. Termasuk koma yang membuntuti setelah impor terakhir dan taruh kurung penutup pada baris itu sendiri.

  Gunakan baris kosong tunggal diantara impor terakhir dan tiap modul kode tingkatan, dan gunakan dua baris kosong diatas fungsi atau kelas pertama.

  Sebagai contoh (komentar hanya untuk tujuan penjelasan):

  *`django/contrib/admin/example.py`*

  ```python
  # future
  from __future__ import unicode_literals

  # standard library
  import json
  from itertools import chain

  # third-party
  import bcrypt

  # Django
  from django.http import Http404
  from django.http.response import (
      Http404,
      HttpResponse,
      HttpResponseNotAllowed,
      StreamingHttpResponse,
      cookie,
  )

  # local Django
  from .models import LogEntry

  # try/except
  try:
      import yaml
  except ImportError:
      yaml = None

  CONSTANT = "foo"

  class Example:
      ...
  ```
- Use convenience imports whenever available. For example, do this

  ```
  from django.views import View
  ```

  dari pada:

  ```
  from django.views.generic.base import View
  ```

## Gaya cetakan

- Di kode cetakan Django, taruh satu (dan hanya satu) spasi diantara kurung keriting dan etiket isi.

  Lakukan ini:

  ```html+django
  {{ foo }}
  ```

  Jangan lakukan ini:

  ```html+django
  {{foo}}
  ```

## Gaya tampilan

- Dalam tampilan Django, parameter pertama dalam sebuah fungsi tampilan harus dipanggil `request`.

  Lakukan ini:

  ```
  def my_view(request, foo):
      ...
  ```

  Jangan lakukan ini:

  ```
  def my_view(req, foo):
      ...
  ```

## Gaya model

- Nama-nama bidang harus semuanya huruf kecil, menggunakan garis bawah daripada camelCase.

  Lakukan ini:

  ```
  class Person(models.Model):
      first_name = models.CharField(max_length=20)
      last_name = models.CharField(max_length=40)
  ```

  Jangan lakukan ini:

  ```
  class Person(models.Model):
      FirstName = models.CharField(max_length=20)
      Last_Name = models.CharField(max_length=40)
  ```
- `class Meta` harus muncul *setelah* bidang ditentukan, dengan baris tunggal kosong memisahkan penentuan bidang-bidang dan kelas

  Lakukan ini:

  ```
  class Person(models.Model):
      first_name = models.CharField(max_length=20)
      last_name = models.CharField(max_length=40)

      class Meta:
          verbose_name_plural = "people"
  ```

  Jangan lakukan ini:

  ```
  class Person(models.Model):
      class Meta:
          verbose_name_plural = "people"

      first_name = models.CharField(max_length=20)
      last_name = models.CharField(max_length=40)
  ```
- Urutan model kelas-kelas sebelah dalam dan cara standar harus sebagai berikut (catat bahwa ini tidak wajib):

  - Semua bidang basisdata
  - Penyesuaian pengelolaan atribut
  - `class Meta`
  - `def __str__()`
  - `def save()`
  - `def get_absolute_url()`
  - Cara penyesuaian apapun
- Jika `choices` ditentukan untuk bidang model diberikan, tentukan setiap pilihan sebagai sebuah daftar dari tuple, dengan nama semua-huruf-besar sebagai atribut kelas. Contoh:

  ```
  class MyModel(models.Model):
      DIRECTION_UP = "U"
      DIRECTION_DOWN = "D"
      DIRECTION_CHOICES = [
          (DIRECTION_UP, "Up"),
          (DIRECTION_DOWN, "Down"),
      ]
  ```

## Penggunaan `django.conf.settings`

Modul-modul tidak harus dalam pengaturan penggunaan umum di `django.conf.settings` pada tingkatan atas (yaitu dinilai ketika modul diimpor). Penjelasan untuk ini adalah sebagai berikut:

Manual configuration of settings (i.e. not relying on the
[`DJANGO_SETTINGS_MODULE`](/id/4.2/topics/settings/#envvar-DJANGO_SETTINGS_MODULE) environment variable) is allowed and possible
as follows:

```
from django.conf import settings

settings.configure({}, SOME_SETTING="foo")
```

Bagaimanapun, jika tiap pengaturan diakses sebelum baris `settings.configure`, ini tidak akan bekerja (Secara internal, `settings` adalah `LazyObject` yang mengkonfigurasikan diri dia sendiri otomatis ketika pengaturan diakses jika dia belum dikonfigurasikan).

Jadi, jika terdapat modul mengandung beberapa kode sebagai berikut:

```
from django.conf import settings
from django.urls import get_callable

default_foo_view = get_callable(settings.FOO_VIEW)
```

...kemudian mengimpor modul ini akan menyebabkan pengaturan obyek untuk dikonfigurasi. Itu berarti bahwa kemampuan untuk pihak ketiga mengimpor modul pada tingkat atas tidak sesuai dengan kemampuan mengkonfigurasi pengaturan obyek secara manual, atau membuatnya sulit di beberapa keadaan.

Sebagai gantinya kode diatas, tingkatan kemalasan atau tipuan harus digunakan, seperti `django.utils.functional.LazyObject`, `django.utils.functional.lazy()` atau `lambda`.

## Bermacam-macam

- Tandai semua deretan karakter untuk internasionalisasi; lihat [i18n documentation](/id/4.2/topics/i18n/) untuk rincian.
- Remove `import` statements that are no longer used when you change code.
  [flake8](https://pypi.org/project/flake8/) will identify these imports for you. If an unused import needs
  to remain for backwards-compatibility, mark the end of with `# NOQA` to
  silence the flake8 warning.
- Secara teratur pindahkan semua ruang kosong dari kode anda dimana mereka menambahkan byte yang tidak dibutuhkan, tambah kekacauan penglihatan pada tambalan dan juga terkadang menyebabkan pertentangan penggabungan yang tidak diperlukan. Beberapa IDE dapat dikonfigurasikan otomatis memindahkan mereka dan kebanyakan alat-alat VCS dapat di setel untuk menyorot mereka di keluaran berbeda.
- Harap jangan menaruh nama anda di kode anda sumbangkan. Kebijakan kami adalah menjaga nama-nama penyumbang di berkas `AUTHORS` disalurkan dengan Django -- bukan goresan melalui basis kode itu sendiri. Merasa bebas untuk menyertakan perubahan pada berkas `AUTHORS` di tambalan anda jika anda membuat lebih dari perubahan sepele tunggal.

## Gaya JavaScript

Untuk rincian tentang gaya kode JavaScript digunakan oleh Django, lihat [JavaScript](/id/4.2/internals/contributing/writing-code/javascript/).
