Bidang formulir¶
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.
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.forms.ValidationError
exception or returns the clean value:
>>> from django import forms
>>> f = forms.EmailField()
>>> f.clean('[email protected]')
'[email protected]'
>>> 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:
>>> 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(' ')
' '
>>> f.clean(0)
'0'
>>> f.clean(True)
'True'
>>> f.clean(False)
'False'
Untuk menentukan bahwa bidang adalah tidak diwajibkan, lewatkan required=False
ke pembangun Field
:
>>> 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 be 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
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 "Outputting forms as HTML" above, 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 label
if that default
behavior doesn't result in an adequate label.
Ini adalah contoh lengkap Form
yang menerapkan label
untuk dua dari bidangnya. Kami telah menentukan auto_id=False
untuk menyederhanakan keluaran:
>>> 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)
<tr><th>Your name:</th><td><input type="text" name="name" required></td></tr>
<tr><th>Your website:</th><td><input type="url" name="url"></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" required></td></tr>
label_suffix
¶
-
Field.
label_suffix
¶
Argumen label_suffix
membuat anda menimpa label_suffix
formulir pada dasar per-bidang:
>>> 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.as_p())
<p><label for="id_age">Age?</label> <input id="id_age" name="age" type="number" required></p>
<p><label for="id_nationality">Nationality?</label> <input id="id_nationality" name="nationality" type="text" required></p>
<p><label for="id_captcha_answer">2 + 2 =</label> <input id="id_captcha_answer" name="captcha_answer" type="number" required></p>
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
.
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:
>>> from django import forms
>>> class CommentForm(forms.Form):
... name = forms.CharField(initial='Your name')
... url = forms.URLField(initial='http://')
... comment = forms.CharField()
>>> f = CommentForm(auto_id=False)
>>> print(f)
<tr><th>Name:</th><td><input type="text" name="name" value="Your name" required></td></tr>
<tr><th>Url:</th><td><input type="url" name="url" value="http://" required></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" required></td></tr>
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:
>>> class CommentForm(forms.Form):
... name = forms.CharField()
... url = forms.URLField()
... comment = forms.CharField()
>>> default_data = {'name': 'Your name', 'url': 'http://'}
>>> f = CommentForm(default_data, auto_id=False)
>>> print(f)
<tr><th>Name:</th><td><input type="text" name="name" value="Your name" required></td></tr>
<tr><th>Url:</th><td><ul class="errorlist"><li>Enter a valid URL.</li></ul><input type="url" name="url" value="http://" required></td></tr>
<tr><th>Comment:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="comment" required></td></tr>
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:
>>> class CommentForm(forms.Form):
... name = forms.CharField(initial='Your name')
... url = forms.URLField(initial='http://')
... comment = forms.CharField()
>>> data = {'name': '', 'url': '', 'comment': 'Foo'}
>>> f = CommentForm(data)
>>> f.is_valid()
False
# The form does *not* fall back 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:
>>> import datetime
>>> class DateForm(forms.Form):
... day = forms.DateField(initial=datetime.date.today)
>>> print(DateForm())
<tr><th>Day:</th><td><input type="text" name="day" value="12/23/2008" required><td></tr>
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 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
, 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:
>>> from django import forms
>>> class HelpTextContactForm(forms.Form):
... subject = forms.CharField(max_length=100, help_text='100 characters max.')
... message = forms.CharField()
... sender = forms.EmailField(help_text='A valid email address, please.')
... cc_myself = forms.BooleanField(required=False)
>>> f = HelpTextContactForm(auto_id=False)
>>> print(f.as_table())
<tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" required><br><span class="helptext">100 characters max.</span></td></tr>
<tr><th>Message:</th><td><input type="text" name="message" required></td></tr>
<tr><th>Sender:</th><td><input type="email" name="sender" required><br>A valid email address, please.</td></tr>
<tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself"></td></tr>
>>> print(f.as_ul()))
<li>Subject: <input type="text" name="subject" maxlength="100" required> <span class="helptext">100 characters max.</span></li>
<li>Message: <input type="text" name="message" required></li>
<li>Sender: <input type="email" name="sender" required> A valid email address, please.</li>
<li>Cc myself: <input type="checkbox" name="cc_myself"></li>
>>> print(f.as_p())
<p>Subject: <input type="text" name="subject" maxlength="100" required> <span class="helptext">100 characters max.</span></p>
<p>Message: <input type="text" name="message" required></p>
<p>Sender: <input type="email" name="sender" required> A valid email address, please.</p>
<p>Cc myself: <input type="checkbox" name="cc_myself"></p>
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:
>>> from django import forms
>>> generic = forms.CharField()
>>> generic.clean('')
Traceback (most recent call last):
...
ValidationError: ['This field is required.']
Dan ini adalah pesan kesalahan penyesuaian:
>>> name = forms.CharField(error_messages={'required': 'Please enter your name'})
>>> name.clean('')
Traceback (most recent call last):
...
ValidationError: ['Please enter your name']
In the built-in Field classes section below, each Field
defines the
error message keys it uses.
validators
¶
-
Field.
validators
¶
Argumen validators
membiarkan anda menyediakan daftar dari fungsi pengecekan untuk bidang ini.
Lihat validators documentation untuk informasi lebih.
localize
¶
-
Field.
localize
¶
The localize
argument enables the localization of form data input, as well
as the rendered output.
Lihat dokuemntasi format localization untuk informasi lebih.
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.
Memeriksa jika data bidang telah berubah¶
has_changed()
¶
The has_changed()
method is used to determine if the field value has changed
from the initial value. Returns True
or False
.
Lihat dokumentasi Form.has_changed()
untuk informasi lebih.
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)[sumber]¶ - Widget awal:
CheckboxInput
- Nilai kosong:
False
- Dinormalkan pada: Nilai Python
True
atauFalse
. - Mensahkan bahwa nilai adalah
True
(misalnya kotak centang dicentang) jika bidang mempunyairequired=True
. - Kunci pesan kesalahan:
required
Catatan
Since all
Field
subclasses haverequired=True
by default, the validation condition here is important. If you want to include a boolean in your form that can be eitherTrue
orFalse
(e.g. a checked or unchecked checkbox), you must remember to pass inrequired=False
when creating theBooleanField
.- Widget awal:
CharField
¶
-
class
CharField
(**kwargs)[sumber]¶ - Widget awal:
TextInput
- Nilai kosong: Apapun anda telah berikan sebagai
empty_value
. - Normalisasikan menjadi: Sebuah string.
- Menggunakan
MaxLengthValidator
danMinLengthValidator
jikamax_length
danmin_length
disediakan. Sebaliknya, semua masukan adalah sah. - Kunci pesan kesalahan:
required
,max_length
,min_length
Mempunyai tiga argumen pilihan untuk pengesahan:
-
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.
- Widget awal:
ChoiceField
¶
-
class
ChoiceField
(**kwargs)[sumber]¶ - Widget awalan:
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 (e.g., a list or tuple) of 2-tuples to use as choices for this field, 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 for more details. If the argument is a callable, it is evaluated each time the field's form is initialized. Defaults to an empty list.
- Widget awalan:
TypedChoiceField
¶
-
class
TypedChoiceField
(**kwargs)[sumber]¶ Just like a
ChoiceField
, exceptTypedChoiceField
takes two extra arguments,coerce
andempty_value
.- Widget awalan:
Select
- Nilai kosong: Apapun anda telah berikan sebagai
empty_value
. - Normalizes to: A value of the type provided by the
coerce
argument. - Validates that the given value exists in the list of choices and can be coerced.
- 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 inchoices
.
-
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 thecoerce
argument, so choose it accordingly.
- Widget awalan:
DateField
¶
-
class
DateField
(**kwargs)[sumber]¶ - Widget awal:
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
¶ A list of formats used to attempt to convert a string to a valid
datetime.date
object.
Jika tidak ada argumen
input_formats
disediakan, bentuk masukan awalan adalah:['%Y-%m-%d', # '2006-10-25' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y'] # '10/25/06'
Additionally, if you specify
USE_L10N=False
in your settings, the following will also be included in the default input formats:['%b %d %Y', # 'Oct 25 2006' '%b %d, %Y', # 'Oct 25, 2006' '%d %b %Y', # '25 Oct 2006' '%d %b, %Y', # '25 Oct, 2006' '%B %d %Y', # 'October 25 2006' '%B %d, %Y', # 'October 25, 2006' '%d %B %Y', # '25 October 2006' '%d %B, %Y'] # '25 October, 2006'
Lihat juga format localization.
- Widget awal:
DateTimeField
¶
-
class
DateTimeField
(**kwargs)[sumber]¶ - Widget awal:
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
¶ A list of formats used to attempt to convert a string to a valid
datetime.datetime
object.
Jika tidak ada argumen
input_formats
disediakan, bentuk masukan awalan adalah:['%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y'] # '10/25/06'
Lihat juga format localization.
- Widget awal:
DecimalField
¶
-
class
DecimalField
(**kwargs)[sumber]¶ - Widget awalan:
NumberInput
ketikaField.localize
adalahFalse
, selain ituTextInput
. - Nilai kosong:
None
- Normalisasikan menjadi: Sebuah
decimal
Python. - Validates that the given value is a decimal. Uses
MaxValueValidator
andMinValueValidator
ifmax_value
andmin_value
are provided. Leading and trailing whitespace is ignored. - Kunci pesan kesalahan:
required
,invalid
,max_value
,min_value
,max_digits
,max_decimal_places
,max_whole_digits
The
max_value
andmin_value
error messages may contain%(limit_value)s
, which will be substituted by the appropriate limit. Similarly, themax_digits
,max_decimal_places
andmax_whole_digits
error messages may contain%(max)s
.Mengambil empat argumen pilihan:
-
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.
- Widget awalan:
DurationField
¶
-
class
DurationField
(**kwargs)[sumber]¶ - Widget awal:
TextInput
- Nilai kosong:
None
- Normalisasikan menjadi: Sebuah
timedelta
Python. - Validates that the given value is a string which can be converted into a
timedelta
. The value must be betweendatetime.timedelta.min
anddatetime.timedelta.max
. - Kunci pesan kesalahan:
required
,invalid
,overflow
.
Menerima bentuk apapun yang dipahami oleh
parse_duration()
.- Widget awal:
EmailField
¶
-
class
EmailField
(**kwargs)[sumber]¶ - Widget awal:
EmailInput
- Nilai kosong:
''
(sebuah deretan karakter kosong) - Normalisasikan menjadi: Sebuah string.
- Uses
EmailValidator
to validate that the given value is a valid email address, using a moderately complex regular expression. - Kunci pesan kesalahan:
required
,invalid
Has two optional arguments for validation,
max_length
andmin_length
. If provided, these arguments ensure that the string is at most or at least the given length.- Widget awal:
FileField
¶
-
class
FileField
(**kwargs)[sumber]¶ - Widget awal:
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 two optional arguments for validation,
max_length
andallow_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.When you use a
FileField
in a form, you must also remember to bind the file data to the form.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.- Widget awal:
FilePathField
¶
-
class
FilePathField
(**kwargs)[sumber]¶ - Widget awalan:
Select
- Nilai kosong:
None
- 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 ofpath
will be offered as choices. IfTrue
, 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
orFalse
. Default isTrue
. Specifies whether files in the specified location should be included. Either this orallow_folders
must beTrue
.
-
allow_folders
¶ Optional. Either
True
orFalse
. Default isFalse
. Specifies whether folders in the specified location should be included. Either this orallow_files
must beTrue
.
- Widget awalan:
FloatField
¶
-
class
FloatField
(**kwargs)[sumber]¶ - Widget awalan:
NumberInput
ketikaField.localize
adalahFalse
, selain ituTextInput
. - Nilai kosong:
None
- Normalisasi menjadi: Sebuah float Python.
- Validates that the given value is a float. Uses
MaxValueValidator
andMinValueValidator
ifmax_value
andmin_value
are provided. Leading and trailing whitespace is allowed, as in Python'sfloat()
function. - Kunci pesan kesalahan:
required
,invalid
,max_value
,min_value
Takes two optional arguments for validation,
max_value
andmin_value
. These control the range of values permitted in the field.- Widget awalan:
ImageField
¶
-
class
ImageField
(**kwargs)[sumber]¶ - Widget awal:
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
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 is installed with support for the image formats you use. If you encounter acorrupt 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.After the field has been cleaned and validated, the
UploadedFile
object will have an additionalimage
attribute containing the Pillow Image instance used to check if the file was a valid image. Also,UploadedFile.content_type
will be updated with the image's content type if Pillow can determine it, otherwise it will be set toNone
.- Widget awal:
IntegerField
¶
-
class
IntegerField
(**kwargs)[sumber]¶ - Widget awalan:
NumberInput
ketikaField.localize
adalahFalse
, selain ituTextInput
. - Nilai kosong:
None
- Normalisasi menjadi: Sebuah integer Python.
- mensahkan bahwa nilai yang diberikan adalah integer. Gunakan
MaxValueValidator
danMinValueValidator
jikamax_value
danmin_value
disediakan. Awalan dan pengekangan ruang putih diijinkan, seeprti dalam fungsiint()
Python. - Kunci pesan kesalahan:
required
,invalid
,max_value
,min_value
The
max_value
andmin_value
error messages may contain%(limit_value)s
, which will be substituted by the appropriate limit.Mengambil dua argumen pilihan untuk pengesahan:
-
max_value
¶
-
min_value
¶
Ini mengendalikan jangkauan nilai yang diizinkan di bidang.
- Widget awalan:
GenericIPAddressField
¶
-
class
GenericIPAddressField
(**kwargs)[sumber]¶ Bidang mengandung antara alamat IPv4 atau IPv6.
- Widget awal:
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.
- Kunci pesan kesalahan:
required
,invalid
Normalisasi alamat IPv6 mengikuti RFC 4291#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 menjadi2001::1
, dan::ffff:0a0a:0a0a
menjadi::ffff:10.10.10.10
. Semau karakter dirubah menjadi huruf kecil.Mengambil dua argumen pilihan:
-
protocol
¶ Membatasi masukan sah pada protokol tertentu. Nilai-nilai diterima adalah
both
(default),IPv4
atauIPv6
. 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 to192.0.2.1
. Default is disabled. Can only be used whenprotocol
is set to'both'
.
- Widget awal:
MultipleChoiceField
¶
-
class
MultipleChoiceField
(**kwargs)[sumber]¶ - Widget awal:
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
, tentangChoiceField
.- Widget awal:
TypedMultipleChoiceField
¶
-
class
TypedMultipleChoiceField
(**kwargs)[sumber]¶ Sama seperti
MultipleChoiceField
, kecualiTypedMultipleChoiceField
mengambil dua argumen tambahan,coerce
danempty_value
.- Widget awal:
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
andempty_value
, as forTypedChoiceField
.- Widget awal:
NullBooleanField
¶
RegexField
¶
-
class
RegexField
(**kwargs)[sumber]¶ - Widget awal:
TextInput
- Nilai kosong:
''
(sebuah deretan karakter kosong) - Normalisasikan menjadi: Sebuah string.
- Uses
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
, andstrip
, which work just as they do forCharField
.-
strip
¶ Defaults to
False
. If enabled, stripping will be applied before the regex validation.
- Widget awal:
SlugField
¶
-
class
SlugField
(**kwargs)[sumber]¶ - Widget awal:
TextInput
- Nilai kosong:
''
(sebuah deretan karakter kosong) - Normalisasikan menjadi: Sebuah string.
- Menggunakan
validate_slug
atauvalidate_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
di formulir.Mengambil sebuah parameter pilihan:
-
allow_unicode
¶ A boolean instructing the field to accept Unicode letters in addition to ASCII letters. Defaults to
False
.
- Widget awal:
TimeField
¶
-
class
TimeField
(**kwargs)[sumber]¶ - Widget awal:
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
¶ A list of formats used to attempt to convert a string to a valid
datetime.time
object.
Jika tidak ada argumen
input_formats
disediakan, bentuk masukan awalan adalah:'%H:%M:%S', # '14:30:59' '%H:%M', # '14:30'
- Widget awal:
URLField
¶
-
class
URLField
(**kwargs)[sumber]¶ - Widget awal:
URLInput
- Nilai kosong:
''
(sebuah deretan karakter kosong) - Normalisasikan menjadi: Sebuah string.
- Uses
URLValidator
to validate that the given value is a valid URL. - Kunci pesan kesalahan:
required
,invalid
Mengambil argumen pilihan berikut:
-
max_length
¶
-
min_length
¶
Ini adalah sama seperti
CharField.max_length
danCharField.min_length
.- Widget awal:
UUIDField
¶
-
class
UUIDField
(**kwargs)[sumber]¶ - Widget awal:
TextInput
- Nilai kosong:
''
(sebuah deretan karakter kosong) - 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 theUUID
constructor.- Widget awal:
Slightly complex built-in Field
classes¶
ComboField
¶
-
class
ComboField
(**kwargs)[sumber]¶ - Widget awal:
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).
>>> from django.forms import ComboField >>> f = ComboField(fields=[CharField(max_length=20), EmailField()]) >>> f.clean('[email protected]') '[email protected]' >>> f.clean('[email protected]') Traceback (most recent call last): ... ValidationError: ['Ensure this value has at most 20 characters (it has 28).']
- Widget awal:
MultiValueField
¶
-
class
MultiValueField
(fields=(), **kwargs)[sumber]¶ - Widget awal:
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
must not implementclean()
but instead - implementcompress()
.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 bycompress()
.
Juga ambil beberapa argumen pilihan:
-
require_all_fields
¶ Defaults to
True
, in which case arequired
validation error will be raised if no value is supplied for any field.When set to
False
, theField.required
attribute can be set toFalse
for individual fields to make them optional. If no value is supplied for a required field, anincomplete
validation error will be raised.A default
incomplete
error message can be defined on theMultiValueField
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
. Default value isTextInput
, which probably is not very useful in this case.
-
compress
(data_list)[sumber]¶ Takes a list of valid values and returns a "compressed" version of those values -- in a single value. For example,
SplitDateTimeField
is a subclass which combines a time field and a date field into adatetime
object.Cara ini harus diterapkan di subkelas.
- Widget awal:
SplitDateTimeField
¶
-
class
SplitDateTimeField
(**kwargs)[sumber]¶ - Widget awal:
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
¶ A list of formats used to attempt to convert a string to a valid
datetime.date
object.
If no
input_date_formats
argument is provided, the default input formats forDateField
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 untukTimeField
adalah yang digunakan.- Widget awal:
Bidang-bidang yang menangani hubungan¶
Two fields are available for representing relationships between
models: ModelChoiceField
and
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 = ...
ModelChoiceField
¶
-
class
ModelChoiceField
(**kwargs)[sumber]¶ - Widget awalan:
Select
- Nilai kosong:
None
- Normalisasi menjadi: Sebuah instance model.
- Mensahkan dimana id diberikan ada dalam queryset.
- Kunci pesan kesalahan:
required
,invalid_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 dua argumen pilihan:-
empty_label
¶ By default the
<select>
widget used byModelChoiceField
will have an empty choice at the top of the list. You can change the text of this label (which is"---------"
by default) with theempty_label
attribute, or you can disable the empty label entirely by settingempty_label
toNone
:# A custom empty label field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)") # No empty label field2 = forms.ModelChoiceField(queryset=..., empty_label=None)
Catat bahwa jika sebuah
ModelChoiceField
diwajibkan dan mempunyai nilai awal awalan, tidak ada pilihan kosong dibuat (meskipun dari nilai dariempty_label
).
-
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:
<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:
<select id="id_field2" name="field2"> <option value="obj1.name">Object1</option> <option value="obj2.name">Object2</option> ... </select>
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, subclassModelChoiceField
and overridelabel_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
- Widget awalan:
ModelMultipleChoiceField
¶
-
class
ModelMultipleChoiceField
(**kwargs)[sumber]¶ - Widget awal:
SelectMultiple
- Nilai kosong: Sebuah (self.queryset.none())
QuerySet
- Normalizes to: A
QuerySet
of model instances. - Mensahkan bahwa setiap id dalam daftar yang diberikan dari nilai ada dalam queryset.
- Kunci pesan kesalahan:
required
,list
,invalid_choice
,invalid_pk_value
Pesan
invalid_choice
mungkin mengandung%(value)s
dan pesaninvalid_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
, anda dapat menggunakanlabel_from_instance
untuk menyesuaikan perwakilan obyek.Argumen tunggal dibutuhkan:
-
queryset
¶ Sama seperti
ModelChoiceField.queryset
.
Mengambil satu argumen pilihan:
-
to_field_name
¶ Sama seperti
ModelChoiceField.to_field_name
.
- Widget awal:
Membuat bidang penyesuaian¶
Jika kelas-kelas Field
siap-pakai tidak memenuhi kebutuhan anda, anda dapat dengan mudah membuat kelas-kelas Field
penyesuaian. Untuk melakukan ini, cukup buat sebuah subkelas dari django.forms.Field
. Persyaratannya hanya bahwa itu menerapkan metode clean()
dan dimana metode __init__()
nya menerima argumen-argumen inti disebutkan diatas (required
, label
, initial
, widget
, help_text
).
Anda dapat juga menyesuaikan bagaimana bidang akan diakses dengan menimpa get_bound_field()
.