---
title: "Gaya pengkodean"
version: 6.0
locale: id
source: https://docs.djangoproject.com/id/6.0/internals/contributing/writing-code/coding-style/
canonical: https://djangodocs.dev/id/6.0/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://pypi.org/project/black/) 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 excludes some 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. We allow up to 88
  characters in code, as this is the line length used by `black`.
  Documentation, comments, and docstrings should be wrapped at 79 characters.
  These limits are checked when `flake8` is run.
- 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/6.0/topics/testing/tools/#django.test.SimpleTestCase.assertRaisesMessage) dan [`assertWarnsMessage()`](/id/6.0/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).
      """
      ...
  ```
- Where applicable, use unpacking generalizations compliant with [**PEP 448**](https://peps.python.org/pep-0448/),
  such as merging mappings (`{**x, **y}`) or sequences (`[*a, *b]`). This
  improves performance, readability, and maintainability while reducing errors.

## Impor

- Gunakan [isort](https://pypi.org/project/isort/) untuk mengotomatisasi pengurutan impor menggunakan panduan dibawah.

  Mulai cepat:

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

  *Windows*

  ```doscon
  ...\> py -m pip install "isort >= 7.0.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
  ```
- Put imports in these groups: future, standard library, third-party libraries,
  other Django components, local Django component, try/excepts. Sort lines in
  each group alphabetically by the full module name. Place all
  `import module` statements before `from module import objects` in each
  section. Use absolute imports for other Django components and a one-dot
  relative import (`from .foo import Bar`) for local components. Avoid
  multi-dot relative imports.
- 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 annotations

  # 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: ...
  ```
- Gunakan impor praktis kapan pun tersedia. Misalnya, lakukan ini

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

  dari pada:

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

## Gaya cetakan

Ikuti aturan dibawah ini dalam kode cetakan Django.

- `{% extends %}` harus menjadi baris non-komentar pertama.

  Lakukan ini:

  ```html+django
  {% extends "base.html" %}

  {% block content %}
    <h1 class="font-semibold text-xl">
      {{ pages.title }}
    </h1>
  {% endblock content %}
  ```

  Atau ini:

  ```html+django
  {# This is a comment #}
  {% extends "base.html" %}

  {% block content %}
    <h1 class="font-semibold text-xl">
      {{ pages.title }}
    </h1>
  {% endblock content %}
  ```

  Jangan lakukan ini:

  ```html+django
  {% load i18n %}
  {% extends "base.html" %}

  {% block content %}
    <h1 class="font-semibold text-xl">
      {{ pages.title }}
    </h1>
  {% endblock content %}
  ```
- Taruh tepatnya satu ruang diantara `{{`, konteks variabel, dan `}}`.

  Lakukan ini:

  ```html+django
  {{ user }}
  ```

  Jangan lakukan ini:

  ```html+django
  {{user}}
  ```
- Di `{% muat ... %}`, daftar pustaka dalam urutan alfabet.

  Lakukan ini:

  ```html+django
  {% load i18n l10 tz %}
  ```

  Jangan lakukan ini:

  ```html+django
  {% load l10 i18n tz %}
  ```
- Put exactly one space between `{%`, tag contents, and `%}`.

  Lakukan ini:

  ```html+django
  {% load humanize %}
  ```

  Jangan lakukan ini:

  ```html+django
  {%load humanize%}
  ```
- Put the `{% block %}` tag name in the `{% endblock %}` tag if it is not
  on the same line.

  Lakukan ini:

  ```html+django
  {% block header %}

    Code goes here

  {% endblock header %}
  ```

  Jangan lakukan ini:

  ```html+django
  {% block header %}

    Code goes here

  {% endblock %}
  ```
- Inside curly braces, separate tokens by single spaces, except for around the
  `.` for attribute access and the `|` for a filter.

  Lakukan ini:

  ```html+django
  {% if user.name|lower == "admin" %}
  ```

  Jangan lakukan ini:

  ```html+django
  {% if user . name | lower  ==  "admin" %}

  {{ user.name | upper }}
  ```
- Within a template using `{% extends %}`, avoid indenting top-level
  `{% block %}` tags.

  Lakukan ini:

  ```html+django
  {% extends "base.html" %}

  {% block content %}
  ```

  Jangan lakukan ini:

  ```html+django
  {% extends "base.html" %}

    {% block content %}
    ...
  ```

## 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__()` dan metode ajaib Python lainnya
  - `def save()`
  - `def get_absolute_url()`
  - Cara penyesuaian apapun
- If `choices` is defined for a given model field, define each choice as a
  mapping, with an all-uppercase name as a class attribute on the model.
  Example:

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

  Alternatifnya, pertimbangkan menggunakan [Enumeration types](/id/6.0/ref/models/fields/#field-choices-enum-types):

  ```
  class MyModel(models.Model):
      class Direction(models.TextChoices):
          UP = "U", "Up"
          DOWN = "D", "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/6.0/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/6.0/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

For details about the JavaScript code style used by Django, see
[Kode JavaScript](/id/6.0/internals/contributing/writing-code/javascript/).
