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

Please follow these coding standards when writing code for inclusion in Django.

## Gaya Phyton

- Please conform to the indentation style dictated in the `.editorconfig`
  file. We recommend using a text editor with [EditorConfig](http://editorconfig.org/) support to avoid
  indentation and whitespace issues. The Python files use 4 spaces for
  indentation and the HTML files use 2 spaces.
- Unless otherwise specified, follow [**PEP 8**](https://peps.python.org/pep-0008/).

  Use [flake8](https://pypi.python.org/pypi/flake8) to check for problems in this area. Note that our `setup.cfg`
  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 119 characters as this is the width of GitHub
  code review; anything longer requires horizontal scrolling which makes review
  more difficult. 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.
- Gunakan empat ruang untuk lekukan.
- Gunakan garis bawah, bukan camelCase, untuk variabel, fungsi dan nama-nama cara (yaitu `poll.get_unique_voters()`, bukan `poll.getUniqueVoters`).
- Use `InitialCaps` for class names (or for factory functions that
  return classes).
- Dalam docstring, ikuti [**PEP 257**](https://peps.python.org/pep-0257/). Sebagai contoh:

  ```
  def foo():
      """
      Calculate something and return the result.
      """
      ...
  ```
- In tests, use [`assertRaisesMessage()`](/id/1.9/topics/testing/tools/#django.test.SimpleTestCase.assertRaisesMessage) instead
  of [`assertRaises()`](https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises) so you can check the exception
  message. Use [`assertRaisesRegex()`](https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaisesRegex)
  (`six.assertRaisesRegex()` as long as we support Python 2) only if you need
  to use regular expression matching.

## Impor

- Gunakan [isort](https://github.com/timothycrosley/isort#readme) untuk mengotomatisasi pengurutan impor menggunakan panduan dibawah.

  Mulai cepat:

  ```console
  $ pip install isort
  $ isort -rc .
  ```

  This runs `isort` recursively from your current directory, modifying any
  files that don't conform to the guidelines. If you need to have imports out
  of order (to avoid a circular import, for example) use a comment like this:

  ```
  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 relative imports for local components.
- On each line, alphabetize the items with the upper case items grouped before
  the lower case items.
- Break long lines using parentheses and indent continuation lines by 4 spaces.
  Include a trailing comma after the last import and put the closing
  parenthesis on its own line.

  Use a single blank line between the last import and any module level code,
  and use two blank lines above the first function or class.

  Sebagai contoh (komentar hanya untuk tujuan penjelasan):

  *django/contrib/admin/example.py*

  ```
  # 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 pytz
  except ImportError:
      pytz = None

  CONSTANT = 'foo'

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

  ```
  from django.views.generic 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)
  ```
- The `class Meta` should appear *after* the fields are defined, with
  a single blank line separating the fields and the class definition.

  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):
      first_name = models.CharField(max_length=20)
      last_name = models.CharField(max_length=40)
      class Meta:
          verbose_name_plural = 'people'
  ```

  Jangan lakukan ini, salah satu:

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

      first_name = models.CharField(max_length=20)
      last_name = models.CharField(max_length=40)
  ```
- If you define a `__str__` method (previously `__unicode__` before Python 3
  was supported), decorate the model class with
  [`python_2_unicode_compatible()`](/id/1.9/ref/utils/#django.utils.encoding.python_2_unicode_compatible).
- The order of model inner classes and standard methods should be as
  follows (noting that these are not all required):

  - Semua bidang basisdata
  - Custom manager attributes
  - `class Meta`
  - `def __str__()`
  - `def save()`
  - `def get_absolute_url()`
  - Cara penyesuaian apapun
- If `choices` is defined for a given model field, define each choice as
  a tuple of tuples, 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'),
      )
  ```

## Penggunaan `django.conf.settings`

Modules should not in general use settings stored in `django.conf.settings`
at the top level (i.e. evaluated when the module is imported). The explanation
for this is as follows:

Manual configuration of settings (i.e. not relying on the
`DJANGO_SETTINGS_MODULE` environment variable) is allowed and possible as
follows:

```
from django.conf import settings

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

However, if any setting is accessed before the `settings.configure` line,
this will not work. (Internally, `settings` is a `LazyObject` which
configures itself automatically when the settings are accessed if it has not
already been configured).

Jadi, jika terdapat modul mengandung beberapa kode sebagai berikut:

```
from django.conf import settings
from django.core.urlresolvers import get_callable

default_foo_view = get_callable(settings.FOO_VIEW)
```

...then importing this module will cause the settings object to be configured.
That means that the ability for third parties to import the module at the top
level is incompatible with the ability to configure the settings object
manually, or makes it very difficult in some circumstances.

Instead of the above code, a level of laziness or indirection must be used,
such as `django.utils.functional.LazyObject`,
`django.utils.functional.lazy()` or `lambda`.

## Bermacam-macam

- Mark all strings for internationalization; see the [i18n
  documentation](/id/1.9/topics/i18n/) for details.
- Remove `import` statements that are no longer used when you change code.
  [flake8](https://pypi.python.org/pypi/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.
- Systematically remove all trailing whitespaces from your code as those
  add unnecessary bytes, add visual clutter to the patches and can also
  occasionally cause unnecessary merge conflicts. Some IDE's can be
  configured to automatically remove them and most VCS tools can be set to
  highlight them in diff outputs.
- Please don't put your name in the code you contribute. Our policy is to
  keep contributors' names in the `AUTHORS` file distributed with Django
  -- not scattered throughout the codebase itself. Feel free to include a
  change to the `AUTHORS` file in your patch if you make more than a
  single trivial change.

## Gaya JavaScript

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