---
title: "Bidang formulir"
version: 6.1
locale: id
source: https://docs.djangoproject.com/id/6.1/ref/forms/fields/
canonical: https://djangodocs.dev/id/6.1/ref/forms/fields/
---
# Bidang formulir

#### `class Field`

When you create a `Form` class, the most important part is defining the
fields of the form. Each field has custom validation logic, along with a few
other hooks.

#### `Field.clean(value)`

Although the primary way you'll use `Field` classes is in `Form` classes,
you can also instantiate them and use them directly to get a better idea of
how they work. Each `Field` instance has a `clean()` method, which takes
a single argument and either raises a
`django.core.exceptions.ValidationError` exception or returns the clean
value:

```pycon
>>> from django import forms
>>> f = forms.EmailField()
>>> f.clean("foo@example.com")
'foo@example.com'
>>> f.clean("invalid email address")
Traceback (most recent call last):
...
ValidationError: ['Enter a valid email address.']
```

## Argumen bidang inti

Each `Field` class constructor takes at least these arguments. Some
`Field` classes take additional, field-specific arguments, but the following
should *always* be accepted:

### `required`

#### `Field.required`

By default, each `Field` class assumes the value is required, so if you pass
an empty value -- either `None` or the empty string (`""`) -- then
`clean()` will raise a `ValidationError` exception:

```pycon
>>> from django import forms
>>> f = forms.CharField()
>>> f.clean("foo")
'foo'
>>> f.clean("")
Traceback (most recent call last):
...
ValidationError: ['This field is required.']
>>> f.clean(None)
Traceback (most recent call last):
...
ValidationError: ['This field is required.']
>>> f.clean(0)
'0'
>>> f.clean(True)
'True'
>>> f.clean(False)
'False'
```

To specify that a field is *not* required, pass `required=False` to the
`Field` constructor:

```pycon
>>> f = forms.CharField(required=False)
>>> f.clean("foo")
'foo'
>>> f.clean("")
''
>>> f.clean(None)
''
>>> f.clean(0)
'0'
>>> f.clean(True)
'True'
>>> f.clean(False)
'False'
```

If a `Field` has `required=False` and you pass `clean()` an empty value,
then `clean()` will return a *normalized* empty value rather than raising
`ValidationError`. For `CharField`, this will return
[`empty_value`](#django.forms.CharField.empty_value) which defaults to an empty string. For other
`Field` classes, it might be `None`. (This varies from field to field.)

Widgets of required form fields have the `required` HTML attribute. Set the
[`Form.use_required_attribute`](/id/6.1/ref/forms/api/#django.forms.Form.use_required_attribute) attribute to `False` to disable it. The
`required` attribute isn't included on forms of formsets because the browser
validation may not be correct when adding and deleting formsets.

### `label`

#### `Field.label`

Argumen `label` membuat anda menentukan label "human-friendly" untuk bidang ini. Ini digunakan ketika `Field` ditampilkan dalam sebuah `Form`.

As explained in [Mengeluarkan formulir sebagai HTML](/id/6.1/ref/forms/api/#ref-forms-api-outputting-html), the default label for a
`Field` is generated from the field name by converting all underscores to
spaces and upper-casing the first letter. Specify a string for `label` if
that default behavior doesn't result in an adequate label. Use an empty string
(`""`) to hide the label.

Here's a full example `Form` that implements `label` for two of its fields.
We've specified `auto_id=False` to simplify the output:

```pycon
>>> from django import forms
>>> class CommentForm(forms.Form):
...     name = forms.CharField(label="Your name")
...     url = forms.URLField(label="Your website", required=False)
...     comment = forms.CharField()
...
>>> f = CommentForm(auto_id=False)
>>> print(f)
<div>Your name:<input type="text" name="name" required></div>
<div>Your website:<input type="url" name="url"></div>
<div>Comment:<input type="text" name="comment" required></div>
```

### `label_suffix`

#### `Field.label_suffix`

The `label_suffix` argument lets you override the form's
[`label_suffix`](/id/6.1/ref/forms/api/#django.forms.Form.label_suffix) on a per-field basis:

```pycon
>>> class ContactForm(forms.Form):
...     age = forms.IntegerField()
...     nationality = forms.CharField()
...     captcha_answer = forms.IntegerField(label="2 + 2", label_suffix=" =")
...
>>> f = ContactForm(label_suffix="?")
>>> print(f)
<div><label for="id_age">Age?</label><input type="number" name="age" required id="id_age"></div>
<div><label for="id_nationality">Nationality?</label><input type="text" name="nationality" required id="id_nationality"></div>
<div><label for="id_captcha_answer">2 + 2 =</label><input type="number" name="captcha_answer" required id="id_captcha_answer"></div>
```

### `initial`

#### `Field.initial`

The `initial` argument lets you specify the initial value to use when
rendering this `Field` in an unbound `Form`.

Untuk menentukan data awal dinamis, lihat parameter [`Form.initial`](/id/6.1/ref/forms/api/#django.forms.Form.initial).

The use-case for this is when you want to display an "empty" form in which a
field is initialized to a particular value. For example:

```pycon
>>> from django import forms
>>> class CommentForm(forms.Form):
...     name = forms.CharField(initial="Your name")
...     url = forms.URLField(initial="https://")
...     comment = forms.CharField()
...
>>> f = CommentForm(auto_id=False)
>>> print(f)
<div>Name:<input type="text" name="name" value="Your name" required></div>
<div>Url:<input type="url" name="url" value="https://" required></div>
<div>Comment:<input type="text" name="comment" required></div>
```

You may be thinking, why not just pass a dictionary of the initial values as
data when displaying the form? Well, if you do that, you'll trigger validation,
and the HTML output will include any validation errors:

```pycon
>>> class CommentForm(forms.Form):
...     name = forms.CharField()
...     url = forms.URLField()
...     comment = forms.CharField()
...
>>> default_data = {"name": "Your name", "url": "https://"}
>>> f = CommentForm(default_data, auto_id=False)
>>> print(f)
<div>Name:
  <input type="text" name="name" value="Your name" required>
</div>
<div>Url:
  <ul class="errorlist"><li>Enter a valid URL.</li></ul>
  <input type="url" name="url" value="https://" required aria-invalid="true">
</div>
<div>Comment:
  <ul class="errorlist"><li>This field is required.</li></ul>
  <input type="text" name="comment" required aria-invalid="true">
</div>
```

This is why `initial` values are only displayed for unbound forms. For bound
forms, the HTML output will use the bound data.

Also note that `initial` values are *not* used as "fallback" data in
validation if a particular field's value is not given. `initial` values are
*only* intended for initial form display:

```pycon
>>> class CommentForm(forms.Form):
...     name = forms.CharField(initial="Your name")
...     url = forms.URLField(initial="https://")
...     comment = forms.CharField()
...
>>> data = {"name": "", "url": "", "comment": "Foo"}
>>> f = CommentForm(data)
>>> f.is_valid()
False
# The form does *not* fallback to using the initial values.
>>> f.errors
{'url': ['This field is required.'], 'name': ['This field is required.']}
```

Instead of a constant, you can also pass any callable:

```pycon
>>> import datetime
>>> class DateForm(forms.Form):
...     day = forms.DateField(initial=datetime.date.today)
...
>>> print(DateForm())
<div><label for="id_day">Day:</label><input type="text" name="day" value="2023-02-11" required id="id_day"></div>
```

The callable will be evaluated only when the unbound form is displayed, not
when it is defined.

### `widget`

#### `Field.widget`

The `widget` argument lets you specify a `Widget` class to use when
rendering this `Field`. See [Widget](/id/6.1/ref/forms/widgets/) for more information.

### `help_text`

#### `Field.help_text`

Argumen `help_text` membiarkan anda menentukan gambaran teks untuk `Field` ini. Jika anda menyediakan `help_text`, itu akan ditampilkan dekat `Field` ketika `Field` dibangun oleh satu dari metode `Form` yang nyaman (misalnya, `as_ul()`).

Like the model field's [`help_text`](/id/6.1/ref/models/fields/#django.db.models.Field.help_text), this value
isn't HTML-escaped in automatically-generated forms.

Here's a full example `Form` that implements `help_text` for two of its
fields. We've specified `auto_id=False` to simplify the output:

```pycon
>>> from django import forms
>>> class HelpTextContactForm(forms.Form):
...     subject = forms.CharField(max_length=100, help_text="100 characters max.")
...     message = forms.CharField()
...     contact_email = forms.EmailField(help_text="Your email (so we can reply).")
...
>>> f = HelpTextContactForm(auto_id=False)
>>> print(f)
<div>Subject:<div class="helptext">100 characters max.</div><input type="text" name="subject" maxlength="100" required></div>
<div>Message:<input type="text" name="message" required></div>
<div>Contact email:<div class="helptext">Your email (so we can reply).</div><input type="email" name="contact_email" maxlength="320" required></div>
```

When a field has help text it is associated with its input using the
`aria-describedby` HTML attribute. If the widget is rendered in a
`<fieldset>` then `aria-describedby` is added to this element, otherwise it
is added to the widget's `<input>`:

```pycon
>>> from django import forms
>>> class UserForm(forms.Form):
...     username = forms.CharField(max_length=255, help_text="e.g., user@example.com")
...
>>> f = UserForm()
>>> print(f)
<div>
<label for="id_username">Username:</label>
<div class="helptext" id="id_username_helptext">e.g., user@example.com</div>
<input type="text" name="username" maxlength="255" required aria-describedby="id_username_helptext" id="id_username">
</div>
```

When adding a custom `aria-describedby` attribute, make sure to also include
the `id` of the `help_text` element (if used) in the desired order. For
screen reader users, descriptions will be read in their order of appearance
inside `aria-describedby`:

```pycon
>>> class UserForm(forms.Form):
...     username = forms.CharField(
...         max_length=255,
...         help_text="e.g., user@example.com",
...         widget=forms.TextInput(
...             attrs={"aria-describedby": "custom-description id_username_helptext"},
...         ),
...     )
...
>>> f = UserForm()
>>> print(f["username"])
<input type="text" name="username" aria-describedby="custom-description id_username_helptext" maxlength="255" id="id_username" required>
```

### `error_messages`

#### `Field.error_messages`

The `error_messages` argument lets you override the default messages that the
field will raise. Pass in a dictionary with keys matching the error messages
you want to override. For example, here is the default error message:

```pycon
>>> from django import forms
>>> generic = forms.CharField()
>>> generic.clean("")
Traceback (most recent call last):
  ...
ValidationError: ['This field is required.']
```

And here is a custom error message:

```pycon
>>> name = forms.CharField(error_messages={"required": "Please enter your name"})
>>> name.clean("")
Traceback (most recent call last):
  ...
ValidationError: ['Please enter your name']
```

Dalam bagian [built-in Field classes](#built-in-field-classes) dibawah ini, setiap `Field` menentukan kunci-kunci pesan kesalahan itu gunakan.

### `validators`

#### `Field.validators`

Argumen `validators` membiarkan anda menyediakan daftar dari fungsi pengecekan untuk bidang ini.

Lihat [validators documentation](/id/6.1/ref/validators/) untuk informasi lebih.

### `localize`

#### `Field.localize`

Argumen `localize` mengadakan lokalisasi dari formulir masukan data, sama halnyakeluaran dibangun.

See the [format localization documentation](/id/6.1/topics/i18n/formatting/) for
more information.

### `disabled`

#### `Field.disabled`

The `disabled` boolean argument, when set to `True`, disables a form field
using the `disabled` HTML attribute so that it won't be editable by users.
Even if a user tampers with the field's value submitted to the server, it will
be ignored in favor of the value from the form's initial data.

### `template_name`

#### `Field.template_name`

The `template_name` argument allows a custom template to be used when the
field is rendered with [`as_field_group()`](/id/6.1/ref/forms/api/#django.forms.BoundField.as_field_group). By
default this value is set to `"django/forms/field.html"`. Can be changed per
field by overriding this attribute or more generally by overriding the default
template, see also [Overriding built-in field templates](/id/6.1/ref/forms/renderers/#overriding-built-in-field-templates).

### `bound_field_class`

#### `Field.bound_field_class`

The `bound_field_class` attribute allows a per-field override of
[`Form.bound_field_class`](/id/6.1/ref/forms/api/#django.forms.Form.bound_field_class).

## Memeriksa jika data bidang telah berubah

### `has_changed()`

#### `Field.has_changed()`

The `has_changed()` method is used to determine if the field value has
changed from the initial value. Returns `True` or `False`.

See the [`Form.has_changed`](/id/6.1/ref/forms/api/#django.forms.Form.has_changed) documentation for more information.

## KelaS-kelas `Field` siap-pakai

Naturally, the `forms` library comes with a set of `Field` classes that
represent common validation needs. This section documents each built-in field.

For each field, we describe the default widget used if you don't specify
`widget`. We also specify the value returned when you provide an empty value
(see the section on `required` above to understand what that means).

### `BooleanField`

#### `class BooleanField(**kwargs)`

- Widget awal: [`CheckboxInput`](/id/6.1/ref/forms/widgets/#django.forms.CheckboxInput)
- Nilai kosong: `False`
- Dinormalkan pada: Nilai Python `True` atau `False`.
- Mensahkan bahwa nilai adalah `True` (misalnya kotak centang dicentang) jika bidang mempunyai `required=True`.
- Kunci pesan kesalahan: `required`

> **Note**
>
> Since all `Field` subclasses have `required=True` by default, the
> validation condition here is important. If you want to include a
> boolean in your form that can be either `True` or `False` (e.g. a
> checked or unchecked checkbox), you must remember to pass in
> `required=False` when creating the `BooleanField`.

### `CharField`

#### `class CharField(**kwargs)`

- Widget awal: [`TextInput`](/id/6.1/ref/forms/widgets/#django.forms.TextInput)
- Nilai kosong: Apapun anda telah berikan sebagai [`empty_value`](#django.forms.CharField.empty_value).
- Normalisasikan menjadi: Sebuah string.
- Menggunakan [`MaxLengthValidator`](/id/6.1/ref/validators/#django.core.validators.MaxLengthValidator) dan [`MinLengthValidator`](/id/6.1/ref/validators/#django.core.validators.MinLengthValidator) jika `max_length` dan `min_length` disediakan. Sebaliknya, semua masukan adalah sah.
- Kunci pesan kesalahan: `required`, `max_length`, `min_length`

Has the following optional arguments for validation:

#### `max_length`

#### `min_length`

If provided, these arguments ensure that the string is at most or at
least the given length.

#### `strip`

Jika `True` (awalan), nilai akan dilucuti dari terkemuka dan buntutan ruang kosong.

#### `empty_value`

NIlai digunakan untuk mewakilkan "empty". Awalan pada string kosong.

### `ChoiceField`

#### `class ChoiceField(**kwargs)`

- Widget awalan: [`Select`](/id/6.1/ref/forms/widgets/#django.forms.Select)
- Nilai kosong: `''` (sebuah deretan karakter kosong)
- Normalisasikan menjadi: Sebuah string.
- Mensahkan yaitu nilai yang diberikan ada dalam daftar pilihan.
- Kunci pesan kesalahan: `required`, `invalid_choice`

The `invalid_choice` error message may contain `%(value)s`, which will
be replaced with the selected choice.

Mengambil satu argumen tambahan:

#### `choices`

Either an [iterable](https://docs.python.org/3/glossary.html#term-iterable) of 2-tuples to use as choices for this
field, [enumeration type](/id/6.1/ref/models/fields/#field-choices-enum-types), or a
callable that returns such an iterable. This argument accepts the same
formats as the `choices` argument to a model field. See the
[model field reference documentation on choices](/id/6.1/ref/models/fields/#field-choices)
for more details. If the argument is a callable, it is evaluated each
time the field's form is initialized, in addition to during rendering.
Defaults to an empty list.

> **Choice type**
>
> This field normalizes choices to strings, so if choices are required in
> other data types, such as integers or booleans, consider using
> [`TypedChoiceField`](#django.forms.TypedChoiceField) instead.

### `DateField`

#### `class DateField(**kwargs)`

- Widget awal: [`DateInput`](/id/6.1/ref/forms/widgets/#django.forms.DateInput)
- Nilai kosong: `None`
- Normalisasikan menjadi: Sebuah obyek `datetime.date` Python.
- Validates that the given value is either a `datetime.date`,
  `datetime.datetime` or string formatted in a particular date format.
- Kunci pesan kesalahan: `required`, `invalid`

Mengambil satu argumen pilihan:

#### `input_formats`

An iterable of formats used to attempt to convert a string to a valid
`datetime.date` object.

If no `input_formats` argument is provided, the default input formats are
taken from the active locale format `DATE_INPUT_FORMATS` key, or from
[`DATE_INPUT_FORMATS`](/id/6.1/ref/settings/#std-setting-DATE_INPUT_FORMATS) if localization is disabled. See also
[format localization](/id/6.1/topics/i18n/formatting/).

### `DateTimeField`

#### `class DateTimeField(**kwargs)`

- Widget awal: [`DateTimeInput`](/id/6.1/ref/forms/widgets/#django.forms.DateTimeInput)
- Nilai kosong: `None`
- Normalisasikan menjadi: Sebuah obyek `datetime.datetime` Python.
- Validates that the given value is either a `datetime.datetime`,
  `datetime.date` or string formatted in a particular datetime format.
- Kunci pesan kesalahan: `required`, `invalid`

Mengambil satu argumen pilihan:

#### `input_formats`

An iterable of formats used to attempt to convert a string to a valid
`datetime.datetime` object, in addition to ISO 8601 formats.

The field always accepts strings in ISO 8601 formatted dates or similar
recognized by [`parse_datetime()`](/id/6.1/ref/utils/#django.utils.dateparse.parse_datetime). Some examples
are:

- `'2006-10-25 14:30:59'`
- `'2006-10-25T14:30:59'`
- `'2006-10-25 14:30'`
- `'2006-10-25T14:30'`
- `'2006-10-25T14:30Z'`
- `'2006-10-25T14:30+02:00'`
- `'2006-10-25'`

If no `input_formats` argument is provided, the default input formats are
taken from the active locale format `DATETIME_INPUT_FORMATS` and
`DATE_INPUT_FORMATS` keys, or from [`DATETIME_INPUT_FORMATS`](/id/6.1/ref/settings/#std-setting-DATETIME_INPUT_FORMATS) and
[`DATE_INPUT_FORMATS`](/id/6.1/ref/settings/#std-setting-DATE_INPUT_FORMATS) if localization is disabled. See also
[format localization](/id/6.1/topics/i18n/formatting/).

### `DecimalField`

#### `class DecimalField(**kwargs)`

- Widget awalan: [`NumberInput`](/id/6.1/ref/forms/widgets/#django.forms.NumberInput) ketika [`Field.localize`](#django.forms.Field.localize) adalah `False`, selain itu [`TextInput`](/id/6.1/ref/forms/widgets/#django.forms.TextInput).
- Nilai kosong: `None`
- Normalisasikan menjadi: Sebuah `decimal` Python.
- Validates that the given value is a decimal. Uses
  [`MaxValueValidator`](/id/6.1/ref/validators/#django.core.validators.MaxValueValidator) and
  [`MinValueValidator`](/id/6.1/ref/validators/#django.core.validators.MinValueValidator) if `max_value` and
  `min_value` are provided. Uses
  [`StepValueValidator`](/id/6.1/ref/validators/#django.core.validators.StepValueValidator) if `step_size` is
  provided. Leading and trailing whitespace is ignored.
- Error message keys: `required`, `invalid`, `max_value`,
  `min_value`, `max_digits`, `max_decimal_places`,
  `max_whole_digits`, `step_size`.

The `max_value` and `min_value` error messages may contain
`%(limit_value)s`, which will be substituted by the appropriate limit.
Similarly, the `max_digits`, `max_decimal_places` and
`max_whole_digits` error messages may contain `%(max)s`.

Takes five optional arguments:

#### `max_value`

#### `min_value`

Ini mengendalikan jangkauan nilai yang diizinkan dalam bidang, dan harus diberikan sebagai nilai `decimal.Decimal`.

#### `max_digits`

The maximum number of digits (those before the decimal point plus those
after the decimal point, with leading zeros stripped) permitted in the
value.

#### `decimal_places`

Angka maksimal dari tempat desimal yang diizinkan.

#### `step_size`

Limit valid inputs to an integral multiple of `step_size`. If
`min_value` is also provided, it's added as an offset to determine if
the step size matches.

### `DurationField`

#### `class DurationField(**kwargs)`

- Widget awal: [`TextInput`](/id/6.1/ref/forms/widgets/#django.forms.TextInput)
- Nilai kosong: `None`
- Normalisasikan menjadi: Sebuah [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) Python.
- Validates that the given value is a string which can be converted into a
  `timedelta`. The value must be between [`datetime.timedelta.min`](https://docs.python.org/3/library/datetime.html#datetime.timedelta.min)
  and [`datetime.timedelta.max`](https://docs.python.org/3/library/datetime.html#datetime.timedelta.max).
- Kunci pesan kesalahan: `required`, `invalid`, `overflow`.

Menerima bentuk apapun yang dipahami oleh [`parse_duration()`](/id/6.1/ref/utils/#django.utils.dateparse.parse_duration).

### `EmailField`

#### `class EmailField(**kwargs)`

- Widget awal: [`EmailInput`](/id/6.1/ref/forms/widgets/#django.forms.EmailInput)
- Empty value: Whatever you've given as `empty_value`.
- Normalisasikan menjadi: Sebuah string.
- Uses [`EmailValidator`](/id/6.1/ref/validators/#django.core.validators.EmailValidator) to validate that
  the given value is a valid email address, using a moderately complex
  regular expression.
- Kunci pesan kesalahan: `required`, `invalid`

Has the optional arguments `max_length`, `min_length`, and
`empty_value` which work just as they do for [`CharField`](#django.forms.CharField). The
`max_length` argument defaults to 320 (see [**RFC 3696 Section 3**](https://datatracker.ietf.org/doc/html/rfc3696.html#section-3)).

### `FileField`

#### `class FileField(**kwargs)`

- Widget awal: [`ClearableFileInput`](/id/6.1/ref/forms/widgets/#django.forms.ClearableFileInput)
- Nilai kosong: `None`
- Normalizes to: An `UploadedFile` object that wraps the file content
  and file name into a single object.
- Can validate that non-empty file data has been bound to the form.
- Kunci pesan kesalahan: `required`, `invalid`, `missing`, `empty`, `max_length`

Has the optional arguments for validation: `max_length` and
`allow_empty_file`. If provided, these ensure that the file name is at
most the given length, and that validation will succeed even if the file
content is empty.

Untuk belajar mengenai obyek `UploadedFile`, lihat [file uploads documentation](/id/6.1/topics/http/file-uploads/).

When you use a `FileField` in a form, you must also remember to
[bind the file data to the form](/id/6.1/ref/forms/api/#binding-uploaded-files).

The `max_length` error refers to the length of the filename. In the error
message for that key, `%(max)d` will be replaced with the maximum
filename length and `%(length)d` will be replaced with the current
filename length.

### `FilePathField`

#### `class FilePathField(**kwargs)`

- Widget awalan: [`Select`](/id/6.1/ref/forms/widgets/#django.forms.Select)
- Nilai kosong: `''` (sebuah deretan karakter kosong)
- Normalisasikan menjadi: Sebuah string.
- Sahkan pilihan terpilih yang ada dalam daftar pilihan.
- Kunci pesan kesalahan: `required`, `invalid_choice`

The field allows choosing from files inside a certain directory. It takes
five extra arguments; only `path` is required:

#### `path`

Jalur mutlak ke pelipat yang isinya anda ingin daftarkan. Pelipat harus ada.

#### `recursive`

If `False` (the default) only the direct contents of `path` will be
offered as choices. If `True`, the directory will be descended into
recursively and all descendants will be listed as choices.

#### `match`

A regular expression pattern; only files with names matching this
expression will be allowed as choices.

#### `allow_files`

Optional. Either `True` or `False`. Default is `True`. Specifies
whether files in the specified location should be included. Either this
or [`allow_folders`](#django.forms.FilePathField.allow_folders) must be `True`.

#### `allow_folders`

Optional. Either `True` or `False`. Default is `False`. Specifies
whether folders in the specified location should be included. Either
this or [`allow_files`](#django.forms.FilePathField.allow_files) must be `True`.

`FilePathField` has the following method:

#### `set_choices()`

> **New in Django 6.1**

Scans the directory at [`path`](#django.forms.FilePathField.path) and refreshes the field's
choices. This is called automatically during `__init__()`, but it can
also be called explicitly to pick up files added to the directory
after the field was first instantiated (usually at server startup). For
example, call it in a form's `__init__()` to get fresh choices per
request:

```
class MyForm(forms.Form):
    my_file = forms.FilePathField(path="/path/to/dir")

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["my_file"].set_choices()
```

### `FloatField`

#### `class FloatField(**kwargs)`

- Widget awalan: [`NumberInput`](/id/6.1/ref/forms/widgets/#django.forms.NumberInput) ketika [`Field.localize`](#django.forms.Field.localize) adalah `False`, selain itu [`TextInput`](/id/6.1/ref/forms/widgets/#django.forms.TextInput).
- Nilai kosong: `None`
- Normalisasi menjadi: Sebuah float Python.
- Validates that the given value is a float. Uses
  [`MaxValueValidator`](/id/6.1/ref/validators/#django.core.validators.MaxValueValidator) and
  [`MinValueValidator`](/id/6.1/ref/validators/#django.core.validators.MinValueValidator) if `max_value` and
  `min_value` are provided. Uses
  [`StepValueValidator`](/id/6.1/ref/validators/#django.core.validators.StepValueValidator) if `step_size` is
  provided. Leading and trailing whitespace is allowed, as in Python's
  `float()` function.
- Error message keys: `required`, `invalid`, `max_value`,
  `min_value`, `step_size`.

Takes three optional arguments:

#### `max_value`

#### `min_value`

Ini mengendalikan jangkauan nilai yang diizinkan di bidang.

#### `step_size`

Limit valid inputs to an integral multiple of `step_size`. If
`min_value` is also provided, it's added as an offset to determine if
the step size matches.

### `GenericIPAddressField`

#### `class GenericIPAddressField(**kwargs)`

Bidang mengandung antara alamat IPv4 atau IPv6.

- Widget awal: [`TextInput`](/id/6.1/ref/forms/widgets/#django.forms.TextInput)
- Nilai kosong: `''` (sebuah deretan karakter kosong)
- Dinormalkan ke: String. Alamat IPv6 dinormalkan seperti digambarkan dibawah.
- Mensahkan bahwa nilai yang diberikan adalah alamat IP sah.
- Error message keys: `required`, `invalid`, `max_length`

Normalisasi alamat IPv6 mengikuti [**RFC 4291 Section 2.2**](https://datatracker.ietf.org/doc/html/rfc4291.html#section-2.2) bagian 2.2, termasuk menggunakan bentuk IPv4 disarankan dalam paragraf 3 dari bagian itu, seperti `::ffff:192.0.2.0`. Sebagai contoh, `2001:0::0:01` akan dinormalkan menjadi `2001::1`, dan `::ffff:0a0a:0a0a` menjadi `::ffff:10.10.10.10`. Semau karakter dirubah menjadi huruf kecil.

Takes three optional arguments:

#### `protocol`

Membatasi masukan sah pada protokol tertentu. Nilai-nilai diterima adalah `both` (default), `IPv4` atau `IPv6`. Cocok adalah kasus tidak peka.

#### `unpack_ipv4`

Unpacks IPv4 mapped addresses like `::ffff:192.0.2.1`.
If this option is enabled that address would be unpacked to
`192.0.2.1`. Default is disabled. Can only be used
when `protocol` is set to `'both'`.

#### `max_length`

Defaults to 39, and behaves the same way as it does for
[`CharField`](#django.forms.CharField).

### `ImageField`

#### `class ImageField(**kwargs)`

- Widget awal: [`ClearableFileInput`](/id/6.1/ref/forms/widgets/#django.forms.ClearableFileInput)
- Nilai kosong: `None`
- Normalizes to: An `UploadedFile` object that wraps the file content
  and file name into a single object.
- Validates that file data has been bound to the form. Also uses
  [`FileExtensionValidator`](/id/6.1/ref/validators/#django.core.validators.FileExtensionValidator) to validate that
  the file extension is supported by Pillow.
- Kunci pesan kesalahan: `required`, `invalid`, `missing`, `empty`, `invalid_image`

Using an `ImageField` requires that [pillow](https://pypi.org/project/pillow/) is installed with
support for the image formats you use. If you encounter a `corrupt image`
error when you upload an image, it usually means that Pillow doesn't
understand its format. To fix this, install the appropriate library and
reinstall Pillow.

Ketika menggunakan `ImageField` pada formulir, anda harus juga mengingat untuk [bind the file data to the form](/id/6.1/ref/forms/api/#binding-uploaded-files).

After the field has been cleaned and validated, the `UploadedFile`
object will have an additional `image` attribute containing the Pillow
[Image](https://pillow.readthedocs.io/en/latest/reference/Image.html) instance used to check if the file was a valid image. Pillow
closes the underlying file descriptor after verifying an image, so while
non-image data attributes, such as `format`, `height`, and `width`,
are available, methods that access the underlying image data, such as
`getdata()` or `getpixel()`, cannot be used without reopening the file.
For example:

```pycon
>>> from PIL import Image
>>> from django import forms
>>> from django.core.files.uploadedfile import SimpleUploadedFile
>>> class ImageForm(forms.Form):
...     img = forms.ImageField()
...
>>> file_data = {"img": SimpleUploadedFile("test.png", b"file data")}
>>> form = ImageForm({}, file_data)
# Pillow closes the underlying file descriptor.
>>> form.is_valid()
True
>>> image_field = form.cleaned_data["img"]
>>> image_field.image
<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=191x287 at 0x7F5985045C18>
>>> image_field.image.width
191
>>> image_field.image.height
287
>>> image_field.image.format
'PNG'
>>> image_field.image.getdata()
# Raises AttributeError: 'NoneType' object has no attribute 'seek'.
>>> image = Image.open(image_field)
>>> image.getdata()
<ImagingCore object at 0x7f5984f874b0>
```

Additionally, `UploadedFile.content_type` will be updated with the
image's content type if Pillow can determine it, otherwise it will be set
to `None`.

### `IntegerField`

#### `class IntegerField(**kwargs)`

- Widget awalan: [`NumberInput`](/id/6.1/ref/forms/widgets/#django.forms.NumberInput) ketika [`Field.localize`](#django.forms.Field.localize) adalah `False`, selain itu [`TextInput`](/id/6.1/ref/forms/widgets/#django.forms.TextInput).
- Nilai kosong: `None`
- Normalisasi menjadi: Sebuah integer Python.
- Validates that the given value is an integer. Uses
  [`MaxValueValidator`](/id/6.1/ref/validators/#django.core.validators.MaxValueValidator) and
  [`MinValueValidator`](/id/6.1/ref/validators/#django.core.validators.MinValueValidator) if `max_value` and
  `min_value` are provided. Uses
  [`StepValueValidator`](/id/6.1/ref/validators/#django.core.validators.StepValueValidator) if `step_size` is
  provided. Leading and trailing whitespace is allowed, as in Python's
  `int()` function.
- Error message keys: `required`, `invalid`, `max_value`,
  `min_value`, `step_size`

The `max_value`, `min_value` and `step_size` error messages may
contain `%(limit_value)s`, which will be substituted by the appropriate
limit.

Takes three optional arguments for validation:

#### `max_value`

#### `min_value`

Ini mengendalikan jangkauan nilai yang diizinkan di bidang.

#### `step_size`

Limit valid inputs to an integral multiple of `step_size`. If
`min_value` is also provided, it's added as an offset to determine if
the step size matches.

### `JSONField`

#### `class JSONField(encoder=None, decoder=None, **kwargs)`

A field which accepts JSON encoded data for a
[`JSONField`](/id/6.1/ref/models/fields/#django.db.models.JSONField).

- Widget awalan: [`Textarea`](/id/6.1/ref/forms/widgets/#django.forms.Textarea)
- Nilai kosong: `None`
- Normalizes to: A Python representation of the JSON value (usually as a
  `dict`, `list`, or `None`), depending on [`JSONField.decoder`](#django.forms.JSONField.decoder).
- Validates that the given value is a valid JSON.
- Kunci pesan kesalahan: `required`, `invalid`

Mengambil dua argumen pilihan:

#### `encoder`

A [`json.JSONEncoder`](https://docs.python.org/3/library/json.html#json.JSONEncoder) subclass to serialize data types not
supported by the standard JSON serializer (e.g. `datetime.datetime`
or [`UUID`](https://docs.python.org/3/library/uuid.html#uuid.UUID)). For example, you can use the
[`DjangoJSONEncoder`](/id/6.1/topics/serialization/#django.core.serializers.json.DjangoJSONEncoder) class.

Awalan untuk `json.JSONEncoder`.

#### `decoder`

A [`json.JSONDecoder`](https://docs.python.org/3/library/json.html#json.JSONDecoder) subclass to deserialize the input. Your
deserialization may need to account for the fact that you can't be
certain of the input type. For example, you run the risk of returning a
`datetime` that was actually a string that just happened to be in the
same format chosen for `datetime`s.

The `decoder` can be used to validate the input. If
[`json.JSONDecodeError`](https://docs.python.org/3/library/json.html#json.JSONDecodeError) is raised during the deserialization,
a `ValidationError` will be raised.

Awalan untuk `json.JSONDecoder`.

> **Note**
>
> If you use a [`ModelForm`](/id/6.1/topics/forms/modelforms/#django.forms.ModelForm), the
> `encoder` and `decoder` from [`JSONField`](/id/6.1/ref/models/fields/#django.db.models.JSONField)
> will be used.

> **Formulir ramah**
>
> `JSONField` is not particularly user friendly in most cases. However,
> it is a useful way to format data from a client-side widget for
> submission to the server.

### `MultipleChoiceField`

#### `class MultipleChoiceField(**kwargs)`

- Widget awal: [`SelectMultiple`](/id/6.1/ref/forms/widgets/#django.forms.SelectMultiple)
- Nilai kosong: `[]` (sebuah deretan karakter kosong)
- Normalisasikan menjadi: Sebuah list dari string.
- Mensahkan bahwa nilai di daftar yang diberikan dari nilai yang ada di daftar pilihan.
- Kunci pesan kesalahan: `required`, `invalid`, `invalid_list`

The `invalid_choice` error message may contain `%(value)s`, which will
be replaced with the selected choice.

Mengambil satu tambahan argumen wajib, `choices`, tentang [`ChoiceField`](#django.forms.ChoiceField).

### `NullBooleanField`

#### `class NullBooleanField(**kwargs)`

- Widget awal: :class:`` `TypedMultipleChoiceField` ``
- Nilai kosong: `None`
- Normalizes to: A Python `True`, `False` or `None` value.
- Validates nothing (i.e., it never raises a `ValidationError`).

`NullBooleanField` may be used with widgets such as
[`Select`](/id/6.1/ref/forms/widgets/#django.forms.Select) or [`RadioSelect`](/id/6.1/ref/forms/widgets/#django.forms.RadioSelect)
by providing the widget `choices`:

```
NullBooleanField(
    widget=Select(
        choices=[
            ("", "Unknown"),
            (True, "Yes"),
            (False, "No"),
        ]
    )
)
```

### `RegexField`

#### `class RegexField(**kwargs)`

- Widget awal: [`TextInput`](/id/6.1/ref/forms/widgets/#django.forms.TextInput)
- Empty value: Whatever you've given as `empty_value`.
- Normalisasikan menjadi: Sebuah string.
- Uses [`RegexValidator`](/id/6.1/ref/validators/#django.core.validators.RegexValidator) to validate that
  the given value matches a certain regular expression.
- Kunci pesan kesalahan: `required`, `invalid`

Mengambil satu argumen diwajibkan:

#### `regex`

A regular expression specified either as a string or a compiled regular
expression object.

Also takes `max_length`, `min_length`, `strip`, and `empty_value`
which work just as they do for [`CharField`](#django.forms.CharField).

#### `strip`

Defaults to `False`. If enabled, stripping will be applied before the
regex validation.

### `SlugField`

#### `class SlugField(**kwargs)`

- Widget awal: [`TextInput`](/id/6.1/ref/forms/widgets/#django.forms.TextInput)
- Nilai kosong: Apapun anda telah berikan sebagai [`empty_value`](#django.forms.SlugField.empty_value).
- Normalisasikan menjadi: Sebuah string.
- Menggunakan [`validate_slug`](/id/6.1/ref/validators/#django.core.validators.validate_slug) atau [`validate_unicode_slug`](/id/6.1/ref/validators/#django.core.validators.validate_unicode_slug) untuk mensahkan bahwa nilai yang diberikan mengandung hanya huruf, angka, garis bawah dan penghubung.
- Pesan kesalahan: `required`, `invalid`.

Bidang ini dimaksudkan untuk digunakan dalam mewakilkan model [`SlugField`](/id/6.1/ref/models/fields/#django.db.models.SlugField) di formulir.

Mengambil dua parameter pilihan:

#### `allow_unicode`

A boolean instructing the field to accept Unicode letters in addition
to ASCII letters. Defaults to `False`.

#### `empty_value`

NIlai digunakan untuk mewakilkan "empty". Awalan pada string kosong.

### `TimeField`

#### `class TimeField(**kwargs)`

- Widget awal: [`TimeInput`](/id/6.1/ref/forms/widgets/#django.forms.TimeInput)
- Nilai kosong: `None`
- Normalisasikan menjadi: Sebuah obyek `datetime.time` Python.
- Validates that the given value is either a `datetime.time` or string
  formatted in a particular time format.
- Kunci pesan kesalahan: `required`, `invalid`

Mengambil satu argumen pilihan:

#### `input_formats`

An iterable of formats used to attempt to convert a string to a valid
`datetime.time` object.

If no `input_formats` argument is provided, the default input formats are
taken from the active locale format `TIME_INPUT_FORMATS` key, or from
[`TIME_INPUT_FORMATS`](/id/6.1/ref/settings/#std-setting-TIME_INPUT_FORMATS) if localization is disabled. See also
[format localization](/id/6.1/topics/i18n/formatting/).

### `TypedChoiceField`

#### `class TypedChoiceField(**kwargs)`

Just like a [`ChoiceField`](#django.forms.ChoiceField), except [`TypedChoiceField`](#django.forms.TypedChoiceField) takes
two extra arguments, [`coerce`](#django.forms.TypedChoiceField.coerce) and [`empty_value`](#django.forms.TypedChoiceField.empty_value).

- Widget awalan: [`Select`](/id/6.1/ref/forms/widgets/#django.forms.Select)
- Nilai kosong: Apapun anda telah berikan sebagai [`empty_value`](#django.forms.TypedChoiceField.empty_value).
- Normalizes to: A value of the type provided by the [`coerce`](#django.forms.TypedChoiceField.coerce)
  argument.
- Mensahkan yang nilai diberikan yang ada dalam daftar pilihan dan dapat dipaksakan.
- Kunci pesan kesalahan: `required`, `invalid_choice`

Mengambil argumen tambahan:

#### `coerce`

A function that takes one argument and returns a coerced value.
Examples include the built-in `int`, `float`, `bool` and other
types. Defaults to an identity function. Note that coercion happens
after input validation, so it is possible to coerce to a value not
present in `choices`.

#### `empty_value`

The value to use to represent "empty." Defaults to the empty string;
`None` is another common choice here. Note that this value will not
be coerced by the function given in the `coerce` argument, so choose
it accordingly.

### `TypedMultipleChoiceField`

#### `class TypedMultipleChoiceField(**kwargs)`

Sama seperti [`MultipleChoiceField`](#django.forms.MultipleChoiceField), kecuali [`TypedMultipleChoiceField`](#django.forms.TypedMultipleChoiceField) mengambil dua argumen tambahan, `coerce` dan `empty_value`.

- Widget awal: [`SelectMultiple`](/id/6.1/ref/forms/widgets/#django.forms.SelectMultiple)
- Nilai kosong: Apapun anda telah berikan sebagai `empty_value`.
- Normalizes to: A list of values of the type provided by the `coerce`
  argument.
- Validates that the given values exists in the list of choices and can be
  coerced.
- Kunci pesan kesalahan: `required`, `invalid_choice`

The `invalid_choice` error message may contain `%(value)s`, which will
be replaced with the selected choice.

Takes two extra arguments, `coerce` and `empty_value`, as for
[`TypedChoiceField`](#django.forms.TypedChoiceField).

### `URLField`

#### `class URLField(**kwargs)`

- Widget awal: [`URLInput`](/id/6.1/ref/forms/widgets/#django.forms.URLInput)
- Empty value: Whatever you've given as `empty_value`.
- Normalisasikan menjadi: Sebuah string.
- Uses [`URLValidator`](/id/6.1/ref/validators/#django.core.validators.URLValidator) to validate that the
  given value is a valid URL.
- Kunci pesan kesalahan: `required`, `invalid`

Has the optional arguments `max_length`, `min_length`, `empty_value`
which work just as they do for [`CharField`](#django.forms.CharField), and one more argument:

#### `assume_scheme`

The scheme assumed for URLs provided without one. Defaults to
`"https"`. For example, if `assume_scheme` is `"https"` and the
provided value is `"example.com"`, the normalized value will be
`"https://example.com"`.

### `UUIDField`

#### `class UUIDField(**kwargs)`

- Widget awal: [`TextInput`](/id/6.1/ref/forms/widgets/#django.forms.TextInput)
- Nilai kosong: `None`
- Normalisasikan menjadi: Sebuah obyek class:~python:uuid.UUID.
- Kunci pesan kesalahan: `required`, `invalid`

This field will accept any string format accepted as the `hex` argument
to the [`UUID`](https://docs.python.org/3/library/uuid.html#uuid.UUID) constructor.

## Slightly complex built-in `Field` classes

### `ComboField`

#### `class ComboField(**kwargs)`

- Widget awal: [`TextInput`](/id/6.1/ref/forms/widgets/#django.forms.TextInput)
- Nilai kosong: `''` (sebuah deretan karakter kosong)
- Normalisasikan menjadi: Sebuah string.
- Validates the given value against each of the fields specified
  as an argument to the `ComboField`.
- Kunci pesan kesalahan: `required`, `invalid`

Mengambil satu argumen tambahan diwajibkan:

#### `fields`

The list of fields that should be used to validate the field's value
(in the order in which they are provided).

```pycon
>>> from django.forms import ComboField
>>> f = ComboField(fields=[CharField(max_length=20), EmailField()])
>>> f.clean("test@example.com")
'test@example.com'
>>> f.clean("longemailaddress@example.com")
Traceback (most recent call last):
...
ValidationError: ['Ensure this value has at most 20 characters (it has 28).']
```

### `MultiValueField`

#### `class MultiValueField(fields=(), **kwargs)`

- Widget awal: [`TextInput`](/id/6.1/ref/forms/widgets/#django.forms.TextInput)
- Nilai kosong: `''` (sebuah deretan karakter kosong)
- Normalizes to: the type returned by the `compress` method of the
  subclass.
- Validates the given value against each of the fields specified
  as an argument to the `MultiValueField`.
- Kunci pesan kesalahan: `required`, `invalid`, `incomplete`

Aggregates the logic of multiple fields that together produce a single
value.

This field is abstract and must be subclassed. In contrast with the
single-value fields, subclasses of [`MultiValueField`](#django.forms.MultiValueField) must not
implement [`clean()`](#django.forms.Field.clean) but instead - implement
[`compress()`](#django.forms.MultiValueField.compress).

Mengambil satu argumen tambahan diwajibkan:

#### `fields`

A tuple of fields whose values are cleaned and subsequently combined
into a single value. Each value of the field is cleaned by the
corresponding field in `fields` -- the first value is cleaned by the
first field, the second value is cleaned by the second field, etc.
Once all fields are cleaned, the list of clean values is combined into
a single value by [`compress()`](#django.forms.MultiValueField.compress).

Juga ambil beberapa argumen pilihan:

#### `require_all_fields`

Defaults to `True`, in which case a `required` validation error
will be raised if no value is supplied for any field.

When set to `False`, the [`Field.required`](#django.forms.Field.required) attribute can be set
to `False` for individual fields to make them optional. If no value
is supplied for a required field, an `incomplete` validation error
will be raised.

A default `incomplete` error message can be defined on the
[`MultiValueField`](#django.forms.MultiValueField) subclass, or different messages can be defined
on each individual field. For example:

```
from django.core.validators import RegexValidator

class PhoneField(MultiValueField):
    def __init__(self, **kwargs):
        # Define one message for all fields.
        error_messages = {
            "incomplete": "Enter a country calling code and a phone number.",
        }
        # Or define a different message for each field.
        fields = (
            CharField(
                error_messages={"incomplete": "Enter a country calling code."},
                validators=[
                    RegexValidator(r"^[0-9]+$", "Enter a valid country calling code."),
                ],
            ),
            CharField(
                error_messages={"incomplete": "Enter a phone number."},
                validators=[RegexValidator(r"^[0-9]+$", "Enter a valid phone number.")],
            ),
            CharField(
                validators=[RegexValidator(r"^[0-9]+$", "Enter a valid extension.")],
                required=False,
            ),
        )
        super().__init__(
            error_messages=error_messages,
            fields=fields,
            require_all_fields=False,
            **kwargs
        )
```

#### `widget`

Must be a subclass of [`django.forms.MultiWidget`](/id/6.1/ref/forms/widgets/#django.forms.MultiWidget).
Default value is [`TextInput`](/id/6.1/ref/forms/widgets/#django.forms.TextInput), which
probably is not very useful in this case.

#### `compress(data_list)`

Takes a list of valid values and returns  a "compressed" version of
those values -- in a single value. For example,
[`SplitDateTimeField`](#django.forms.SplitDateTimeField) is a subclass which combines a time field
and a date field into a `datetime` object.

Cara ini harus diterapkan di subkelas.

### `SplitDateTimeField`

#### `class SplitDateTimeField(**kwargs)`

- Widget awal: [`SplitDateTimeWidget`](/id/6.1/ref/forms/widgets/#django.forms.SplitDateTimeWidget)
- Nilai kosong: `None`
- Normalisasikan menjadi: Sebuah obyek `datetime.datetime` Python.
- Mensahkan bahwa nilai yang diberikan adalah berbentuk `datetime.datetime` atau string dalam bentuk datetime khusus.
- Kunci pesan kesalahan: `required`, `invalid`, `invalid_date`, `invalid_time`

Mengambil dua argumen pilihan:

#### `input_date_formats`

Sebuah daftar dari bentuk untuk berusaha merubah sebuah string menjadi obyek `datetime.date` sah.

If no `input_date_formats` argument is provided, the default input
formats for [`DateField`](#django.forms.DateField) are used.

#### `input_time_formats`

A list of formats used to attempt to convert a string to a valid
`datetime.time` object.

Jika tidak ada argumen `input_time_formats` disediakan, bentuk masukan awalan untuk [`TimeField`](#django.forms.TimeField) adalah yang digunakan.

## Bidang-bidang yang menangani hubungan

Two fields are available for representing relationships between
models: [`ModelChoiceField`](#django.forms.ModelChoiceField) and
[`ModelMultipleChoiceField`](#django.forms.ModelMultipleChoiceField). Both of these fields require a
single `queryset` parameter that is used to create the choices for
the field. Upon form validation, these fields will place either one
model object (in the case of `ModelChoiceField`) or multiple model
objects (in the case of `ModelMultipleChoiceField`) into the
`cleaned_data` dictionary of the form.

Untuk penggunaan lebih rumit, anda dapat menentukan `queryset=None` ketika menyatakan bidang formulir dan kemudian mengumpulkan `queryset` dalam metode `__init__()` formulir:

```
class FooMultipleChoiceForm(forms.Form):
    foo_select = forms.ModelMultipleChoiceField(queryset=None)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["foo_select"].queryset = ...
```

Both `ModelChoiceField` and `ModelMultipleChoiceField` have an `iterator`
attribute which specifies the class used to iterate over the queryset when
generating choices. See [Iterating relationship choices](#iterating-relationship-choices) for details.

### `ModelChoiceField`

#### `class ModelChoiceField(**kwargs)`

- Widget awalan: [`Select`](/id/6.1/ref/forms/widgets/#django.forms.Select)
- Nilai kosong: `None`
- Normalisasi menjadi: Sebuah instance model.
- Mensahkan dimana id diberikan ada dalam queryset.
- Kunci pesan kesalahan: `required`, `invalid_choice`

The `invalid_choice` error message may contain `%(value)s`, which will
be replaced with the selected choice.

Mengizinkan pemilihan dari obyek model tunggal, cocok untuk mewakili sebuah foreign-key. Catat bahwa widget awalan untuk `ModelChoiceField` menjadi tidak praktis ketika angka dari masukan meningkat. Anda harus menghindari menggunakan itu untuk lebih dari 100 barang.

Argumen tunggal dibutuhkan:

#### `queryset`

Sebuah `QuerySet` obyek model dimana pilihan untuk bidang adalah diturunkan dan dimana digunakan untuk mensahkan pemilihan pengguna. Itu dinilai ketika formulir dibangun.

`ModelChoiceField` juga mengambil beberapa pilihan argumen:

#### `empty_label`

By default the `<select>` widget used by `ModelChoiceField` will
have an empty choice at the top of the list. You can change the text of
this label (which is `"- Select an option -"` by default) with the
`empty_label` attribute, or you can disable the empty label entirely
by setting `empty_label` to `None`:

```
# A custom empty label
field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)")

# No empty label
field2 = forms.ModelChoiceField(queryset=..., empty_label=None)
```

Note that no empty choice is created (regardless of the value of
`empty_label`) if a `ModelChoiceField` is required and has a
default initial value, or a `widget` is set to
[`RadioSelect`](/id/6.1/ref/forms/widgets/#django.forms.RadioSelect) and the
[`blank`](#django.forms.ModelChoiceField.blank) argument is `False`.

> **Changed in Django 6.1**
>
> The default empty label was changed from `"---------"` to
> `"- Select an option -"`.

#### `to_field_name`

This optional argument is used to specify the field to use as the value
of the choices in the field's widget. Be sure it's a unique field for
the model, otherwise the selected value could match more than one
object. By default it is set to `None`, in which case the primary key
of each object will be used. For example:

```
# No custom to_field_name
field1 = forms.ModelChoiceField(queryset=...)
```

akan menghasilkan:

```html
<select id="id_field1" name="field1">
<option value="obj1.pk">Object1</option>
<option value="obj2.pk">Object2</option>
...
</select>
```

dan:

```
# to_field_name provided
field2 = forms.ModelChoiceField(queryset=..., to_field_name="name")
```

akan menghasilkan:

```html
<select id="id_field2" name="field2">
<option value="obj1.name">Object1</option>
<option value="obj2.name">Object2</option>
...
</select>
```

#### `blank`

When using the [`RadioSelect`](/id/6.1/ref/forms/widgets/#django.forms.RadioSelect) widget, this optional
boolean argument determines whether an empty choice is created. By
default, `blank` is `False`, in which case no empty choice is
created.

`ModelChoiceField` also has the attribute:

#### `iterator`

The iterator class used to generate field choices from `queryset`. By
default, [`ModelChoiceIterator`](#django.forms.ModelChoiceIterator).

The `__str__()` method of the model will be called to generate string
representations of the objects for use in the field's choices. To provide
customized representations, subclass `ModelChoiceField` and override
`label_from_instance`. This method will receive a model object and should
return a string suitable for representing it. For example:

```
from django.forms import ModelChoiceField

class MyModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return "My Object #%i" % obj.id
```

### `ModelMultipleChoiceField`

#### `class ModelMultipleChoiceField(**kwargs)`

- Widget awal: [`SelectMultiple`](/id/6.1/ref/forms/widgets/#django.forms.SelectMultiple)
- Empty value: An empty `QuerySet` (`self.queryset.none()`)
- Normalizes to: A `QuerySet` of model instances.
- Mensahkan bahwa setiap id dalam daftar yang diberikan dari nilai ada dalam queryset.
- Error message keys: `required`, `invalid_list`, `invalid_choice`,
  `invalid_pk_value`

Pesan `invalid_choice` mungkin mengandung `%(value)s` dan pesan `invalid_pk_value` mungkin mengandung `%(pk)s`, yang akan diganti oleh nilai-nilai sesuai.

Mengizinkan pemilihan satu atau lebih obyek model, cocok untuk mewakili hubungan many-to-many. Seperti dengan [`ModelChoiceField`](#django.forms.ModelChoiceField), anda dapat menggunakan `label_from_instance` untuk menyesuaikan perwakilan obyek.

Argumen tunggal dibutuhkan:

#### `queryset`

Sama seperti [`ModelChoiceField.queryset`](#django.forms.ModelChoiceField.queryset).

Mengambil satu argumen pilihan:

#### `to_field_name`

Sama seperti [`ModelChoiceField.to_field_name`](#django.forms.ModelChoiceField.to_field_name).

`ModelMultipleChoiceField` also has the attribute:

#### `iterator`

Same as [`ModelChoiceField.iterator`](#django.forms.ModelChoiceField.iterator).

### Iterating relationship choices

By default, [`ModelChoiceField`](#django.forms.ModelChoiceField) and [`ModelMultipleChoiceField`](#django.forms.ModelMultipleChoiceField) use
[`ModelChoiceIterator`](#django.forms.ModelChoiceIterator) to generate their field `choices`.

When iterated, `ModelChoiceIterator` yields 2-tuple choices containing
[`ModelChoiceIteratorValue`](#django.forms.ModelChoiceIteratorValue) instances as the first `value` element in
each choice. `ModelChoiceIteratorValue` wraps the choice value while
maintaining a reference to the source model instance that can be used in custom
widget implementations, for example, to add [data-\* attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-*) to
`<option>` elements.

For example, consider the following models:

```
from django.db import models

class Topping(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(decimal_places=2, max_digits=6)

    def __str__(self):
        return self.name

class Pizza(models.Model):
    topping = models.ForeignKey(Topping, on_delete=models.CASCADE)
```

You can use a [`Select`](/id/6.1/ref/forms/widgets/#django.forms.Select) widget subclass to include
the value of `Topping.price` as the HTML attribute `data-price` for each
`<option>` element:

```
from django import forms

class ToppingSelect(forms.Select):
    def create_option(
        self, name, value, label, selected, index, subindex=None, attrs=None
    ):
        option = super().create_option(
            name, value, label, selected, index, subindex, attrs
        )
        if value:
            option["attrs"]["data-price"] = value.instance.price
        return option

class PizzaForm(forms.ModelForm):
    class Meta:
        model = Pizza
        fields = ["topping"]
        widgets = {"topping": ToppingSelect}
```

This will render the `Pizza.topping` select as:

```html
<select id="id_topping" name="topping" required>
<option value="" selected>---------</option>
<option value="1" data-price="1.50">mushrooms</option>
<option value="2" data-price="1.25">onions</option>
<option value="3" data-price="1.75">peppers</option>
<option value="4" data-price="2.00">pineapple</option>
</select>
```

For more advanced usage you may subclass `ModelChoiceIterator` in order to
customize the yielded 2-tuple choices.

#### `ModelChoiceIterator`

#### `class ModelChoiceIterator(field)`

The default class assigned to the `iterator` attribute of
[`ModelChoiceField`](#django.forms.ModelChoiceField) and [`ModelMultipleChoiceField`](#django.forms.ModelMultipleChoiceField). An
iterable that yields 2-tuple choices from the queryset.

Argumen tunggal dibutuhkan:

#### `field`

The instance of `ModelChoiceField` or `ModelMultipleChoiceField` to
iterate and yield choices.

`ModelChoiceIterator` has the following method:

#### `__iter__()`

Yields 2-tuple choices, in the `(value, label)` format used by
[`ChoiceField.choices`](#django.forms.ChoiceField.choices). The first `value` element is a
[`ModelChoiceIteratorValue`](#django.forms.ModelChoiceIteratorValue) instance.

#### `ModelChoiceIteratorValue`

#### `class ModelChoiceIteratorValue(value, instance)`

Two arguments are required:

#### `value`

The value of the choice. This value is used to render the `value`
attribute of an HTML `<option>` element.

#### `instance`

The model instance from the queryset. The instance can be accessed in
custom `ChoiceWidget.create_option()` implementations to adjust the
rendered HTML.

`ModelChoiceIteratorValue` has the following method:

#### `__str__()`

Return `value` as a string to be rendered in HTML.

## Membuat bidang penyesuaian

If the built-in `Field` classes don't meet your needs, you can create custom
`Field` classes. To do this, create a subclass of `django.forms.Field`. Its
only requirements are that it implement a `clean()` method and that its
`__init__()` method accept the core arguments mentioned above (`required`,
`label`, `initial`, `widget`, `help_text`).

You can also customize how a field will be accessed by overriding
[`bound_field_class`](#django.forms.Field.bound_field_class) or override
[`Field.get_bound_field()`](#django.forms.Field.get_bound_field) if you need more flexibility when creating
the `BoundField`:

#### `Field.get_bound_field(form, field_name)`

Takes an instance of [`Form`](/id/6.1/ref/forms/api/#django.forms.Form) and the name of the field.
The returned [`BoundField`](/id/6.1/ref/forms/api/#django.forms.BoundField) instance will be used when accessing the
field in a template.

See [Menyesuaikan BoundField](/id/6.1/ref/forms/api/#custom-boundfield) for examples of overriding a `BoundField`.
