---
title: "Na Foirmeacha API"
version: 6.0
locale: ga
source: https://docs.djangoproject.com/ga/6.0/ref/forms/api/
canonical: https://djangodocs.dev/ga/6.0/ref/forms/api/
---
# Na Foirmeacha API

> **Maidir leis an doiciméad seo**
>
> Clúdaíonn an doiciméad seo sonraí crua API foirmeacha Django. Ba chóir duit:doc: réamhrá ar obair le foirmeacha 'a léamh ar dtús \</topics/forms/index\>.

## Foirmeacha ceangailte agus gan cheangal

A: Aicme: Is é an sampla Foirme **teorann** le tacar sonraí, nó **gan teorann**.

- Má tá sé **teorann** le tacar sonraí, tá sé in ann na sonraí sin a bhailíochtú agus an fhoirm a léiriú mar HTML leis na sonraí a thaispeántar sa HTML.
- Má tá sé\*\*gan teorann\*\*, ní féidir leis bailíochtú a dhéanamh (toisc nach bhfuil aon sonraí le bailíochtú!) , ach is féidir leis an bhfoirm bán a rinneadh mar HTML fós.

#### `class Form`

Chun sampla untheor:class: Form a chruthú, déan an rang a chur isteach:

```pycon
>>> f = ContactForm()
```

Chun sonraí a cheangal le foirm, cuir na sonraí mar fhoclóir mar an chéad pharaiméadar chuig do thógálaí aicme:class: Form:

```pycon
>>> data = {
...     "subject": "hello",
...     "message": "Hi there",
...     "contact_email": "foo@example.com",
...     "urgent": True,
... }
>>> f = ContactForm(data)
```

Sa bhfoclóir seo, is iad na heochracha na hainmneacha réimse, a fhreagraíonn do na tréithe i d'aicme:class: Form. Is iad na luachanna na sonraí atá tú ag iarraidh a bhailíochtú. Is teaghráin iad seo de ghnáth, ach níl aon cheanglas ann gur teaghráin iad; braitheann an cineál sonraí a chuireann tú ar: aicme: Field, mar a fheicfimid i gceann nóiméad.

#### `Form.is_bound`

Más gá duit idirdhealú a dhéanamh idir cásanna foirme ceangailte agus neamhcheangailte ag an am rith, seiceáil luach na tréithe foirme's:attr: ~form.is\_bound:

```pycon
>>> f = ContactForm()
>>> f.is_bound
False
>>> f = ContactForm({"subject": "hello"})
>>> f.is_bound
True
```

Tabhair faoi deara go gcruthaíonn foirm\*teorann\* le sonraí folamh a rith le foclóir folamh:

```pycon
>>> f = ContactForm({})
>>> f.is_bound
True
```

Má tá sampla teorain:class: Form agat agus má theastaíonn uait na sonraí a athrú ar bhealach éigin, nó más mian leat sampla untheor:class: Form a cheangal le roinnt sonraí, cruthaigh sampla eile: class: Form. Níl aon bhealach ann chun sonraí a athrú i gcás a:class: Form. Nuair a cruthaíodh a: aicme: Form sampla, ba cheart duit a shonraí a mheas gan athrú, cibé acu tá sonraí aige nó nach bhfuil.

## Foirmeacha a úsáid chun sonraí a bhailíochtú

#### `Form.clean()`

Cuir modh glan () i bhfeidhm ar do Foirm nuair a chaithfidh tú bailíochtú saincheaptha a chur le haghaidh réimsí atá idirspleáchach. Féach: ref: validating-fields-with-glan mar shampla úsáid.

#### `Form.is_valid()`

Is é príomhthasc a: aicme: Form ná sonraí a bhailíochtú. Le sampla teorain:class: Form, glaoigh ar an modh:meth: ~form.is\_valid chun bailíochtú a reáchtáil agus boolean a thabhairt ar ais ag ainmniú an raibh na sonraí bailí:

```pycon
>>> data = {
...     "subject": "hello",
...     "message": "Hi there",
...     "contact_email": "foo@example.com",
...     "urgent": True,
... }
>>> f = ContactForm(data)
>>> f.is_valid()
True
```

Let's try with some invalid data. In this case, `subject` is blank (an error,
because all fields are required by default) and `contact_email` is not a
valid email address:

```pycon
>>> data = {
...     "subject": "",
...     "message": "Hi there",
...     "contact_email": "invalid email address",
...     "urgent": True,
... }
>>> f = ContactForm(data)
>>> f.is_valid()
False
```

#### `Form.errors`

Rochtain ar thréith :attr: ~form.errors chun foclóir teachtaireachtaí earráide a fháil:

```pycon
>>> f.errors
{'subject': ['This field is required.'],
 'contact_email': ['Enter a valid email address.']}
```

Sa fhoclóir seo, is iad na heochracha na hainmneacha réimse, agus is liostaí teaghráin iad na luachanna a léiríonn na teachtaireachtaí earráide. Stóráiltear na teachtaireachtaí earráide i liostaí toisc go bhféadfadh teachtaireachtaí earráide iliomad a bheith

Is féidir leat rochtain a fháil ar: attr: ~form.errors gan glaoch ar: meth: ~form.is\_valid ar dtús. Déanfar sonraí na foirme a bhailíochtú an chéad uair a ghlaonn tú ar: meth: ~form.is\_valid nó access:attr: ~form.errors.

Ní ghlaofar ar na gnáthaimh bailíochtaithe ach uair amháin, is cuma cé mhéad uair a rochtain agat ar: attr: ~form.errors nó glao:meth: ~form.is\_valid. Ciallaíonn sé seo má tá fo-iarsmaí ag bailíochtú, ní spreagfar na fo-iarsmaí sin ach uair amháin.

#### `Form.errors.as_data()`

Faigheann `dict` ar ais a léarscáil réimsí chuig a gcásanna bunaidh `ValidationError`.

```pycon
>>> f.errors.as_data()
{'subject': [ValidationError(['This field is required.'])],
 'contact_email': [ValidationError(['Enter a valid email address.'])]}
```

Use this method anytime you need to identify an error by its `code`. This
enables things like rewriting the error's message or writing custom logic in a
view when a given error is present. It can also be used to serialize the errors
in a custom format (e.g. XML); for instance, [`as_json()`](#django.forms.Form.errors.as_json)
relies on `as_data()`.

Tá an gá atá le modh ```as_data () ``mar gheall ar chomhoiriúnacht ar ais. Cailleadh cásanna ``ValidationError``` roimhe seo chomh luath agus a gcuid teachtaireachtaí earráide a rinneadh leis an bhfoclóir `Form.errors`. Go hidéalach bheadh Form.errors\` stóráilte cásanna agus modhanna `ValidationError` le réimír `as_` iad a dhéanamh, ach b'éigean é a dhéanamh ar an mbealach eile d'fhonn gan cód a bhriseadh a bhfuil súil le teachtaireachtaí earráide a rinneadh i Form.errors\`.

#### `Form.errors.as_json(escape_html=False)`

Returns a string with the errors serialized as JSON.

```pycon
>>> f.errors.as_json()
'{"subject": [{"message": "This field is required.", "code": "required"}],
 "contact_email": [{"message": "Enter a valid email address.", "code": "invalid"}]}'
```

De réir réamhshocraithe, ní éalaíonn ```as_json () ``a aschur. Má tá tú á úsáid le haghaidh rud éigin cosúil le hiarratais AJAX chuig amharc foirme ina ndéanann an cliant an freagra a léirmhíniú agus earráidí isteach sa leathanach, beidh tú ag iarraidh a bheith cinnte go n-éalóidh tú na torthaí ar thaobh an chliaint chun an fhéidearthacht ionsaí scripteála tras-láithreáin a sheachaint. Is féidir leat é seo a dhéanamh i JavaScript le ``Element.textContent = ErrorText``` nó le ```$ (el) .text (ErrorText) ``jQuery (seachas a fheidhm ``.html ()```).

Mura dteastaíonn uait éalú taobh an chliaint a úsáid ar chúis éigin, is féidir leat `escape_html = true` a shocrú freisin agus éalófar teachtaireachtaí earráide ionas gur féidir leat iad a úsáid go díreach i HTML.

#### `Form.errors.get_json_data(escape_html=False)`

Returns the errors as a dictionary suitable for serializing to JSON.
[`Form.errors.as_json()`](#django.forms.Form.errors.as_json) returns serialized JSON, while this returns the
error data before it's serialized.

The `escape_html` parameter behaves as described in
[`Form.errors.as_json()`](#django.forms.Form.errors.as_json).

#### `Form.add_error(field, error)`

Ligeann an modh seo earráidí a chur le réimsí ar leith ón modh Form.clean () , nó ón taobh amuigh den fhoirm ar fad; mar shampla ó radharc.

Is é an argóint `réimse` ainm an réimse ar chóir na hearráidí a chur leis. \<django.forms.Form.non\_field\_errors\>Más é a luach `None`, déileálfar leis an earráid mar earráid neamh-réimse mar a d'fhaigh:meth: form.non\_field\_errors () .

Is féidir leis an argóint `earráid` a bheith ina shreang, nó b'fhéidir mar shampla de `ValidationError`. Féach:ref: earrá-bhailíochtai-earráid le haghaidh dea-chleachtais agus earráidí foirme á sainmhíniú.

Tabhair faoi deara go mbaineann ```form.add_error () ``an réimse ábhartha go huathoibríoch ó ``cleaned_data```.

#### `Form.has_error(field, code=None)`

Tugann an modh seo boolean ar ais ag ainmniú an bhfuil earráid i réimse le earráid sonrach ````cód ``. Más é ```Cód ```None````, fillfidh sé `True` má tá aon earráidí sa réimse ar chor ar bith.

Chun seiceáil le haghaidh earráidí neamh-réimse bain úsáid as: data: ~django.core.EXCEPTIONS.NON\_FIELD\_ERRORS mar an paraiméadar `field`.

#### `Form.non_field_errors()`

Tugann an modh seo an liosta earráidí ó:attr: Form.errors \<django.forms.Form.errors\>\`nach bhfuil baint acu le réimse áirithe. Áirítear leis seo \`\`ValidationError\`s a ardaítear in:meth: Form.clean () \`agus earráidí curtha leis ag baint úsáid:meth: \`Form.add\_error (None, \<django.forms.Form.clean\>“...”) \<django.forms.Form.add\_error\>.

### Iompar foirmeacha neamhcheangailte

Tá sé gan chiall foirm a bhailíochtú gan aon sonraí, ach, chun an taifead, seo cad a tharlaíonn le foirmeacha neamhcheangailte:

```pycon
>>> f = ContactForm()
>>> f.is_valid()
False
>>> f.errors
{}
```

## Luachanna foirme tosaigh

#### `Form.initial`

Úsáid: Attr: ~Form.Initial chun luach tosaigh réimsí foirme a dhearbhú ag an am rith. Mar shampla, b'fhéidir gur mhaith leat réimse ainm úsáideora a líonadh isteach le hainm úsáideora an tseisiúin reatha.

Chun é seo a chur i gcrích, bain úsáid as an argóint:attr: ~form.initial chuig a:class: Form. Ba chóir go mbeadh an argóint seo, má thugtar, ina fhoclóir a mhapáil ainmneacha réimse go luachanna Cuir san áireamh ach na réimsí a bhfuil luach tosaigh á shonrú agat dóibh; ní gá gach réimse a áireamh i d'fhoirm. Mar shampla:

```pycon
>>> f = ContactForm(initial={"subject": "Hi there!"})
```

Ní thaispeántar na luachanna seo ach le haghaidh foirmeacha neamhcheangailte, agus ní úsáidtear iad mar luachanna cúltaca mura gcuirtear luach ar leith ar fáil.

Má shainmhíníonn a:class: ~django.forms.field: attr: ~Field.Initial *agus* san áireamh tuat:attr: ~form.initial agus an Form\` á gcur isteach agat, ansin beidh tosaíocht ag an deireanach `initial`. Sa sampla seo, soláthraítear `tosaithe` ag leibhéal an réimse agus ag leibhéal na foirme araon, agus faigheann an dara ceann tosaíocht:

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

#### `Form.get_initial_for_field(field, field_name)`

Tugann na sonraí tosaigh ar ais do réimse foirme. Aisghabhann sé na sonraí ó:attr: Form.initial má tá sé i láthair, ar shlí eile iarracht: attr: Field.initial. Déantar luachanna inghlaonta a mheas.

It is recommended to use [`BoundField.initial`](#django.forms.BoundField.initial) over
[`get_initial_for_field()`](#django.forms.Form.get_initial_for_field) because `BoundField.initial` has a
simpler interface. Also, unlike [`get_initial_for_field()`](#django.forms.Form.get_initial_for_field),
[`BoundField.initial`](#django.forms.BoundField.initial) caches its values. This is useful especially when
dealing with callables whose return values can change (e.g. `datetime.now` or
`uuid.uuid4`):

```pycon
>>> import uuid
>>> class UUIDCommentForm(CommentForm):
...     identifier = forms.UUIDField(initial=uuid.uuid4)
...
>>> f = UUIDCommentForm()
>>> f.get_initial_for_field(f.fields["identifier"], "identifier")
UUID('972ca9e4-7bfe-4f5b-af7d-07b3aa306334')
>>> f.get_initial_for_field(f.fields["identifier"], "identifier")
UUID('1b411fab-844e-4dec-bd4f-e9b0495f04d0')
>>> # Using BoundField.initial, for comparison
>>> f["identifier"].initial
UUID('28a09c59-5f00-4ed9-9179-a3b074fa9c30')
>>> f["identifier"].initial
UUID('28a09c59-5f00-4ed9-9179-a3b074fa9c30')
```

## Seiceáil cén fhoirm sonraí atá athraithe

#### `Form.has_changed()`

Úsáid an modh ```has_changed () ``ar do `Foirm``` nuair is gá duit a sheiceáil an bhfuil sonraí na foirme athraithe ó na sonraí tosaigh.

```pycon
>>> data = {
...     "subject": "hello",
...     "message": "Hi there",
...     "contact_email": "foo@example.com",
...     "urgent": True,
... }
>>> f = ContactForm(data, initial=data)
>>> f.has_changed()
False
```

Nuair a chuirtear an fhoirm isteach, déanaimid í a athchógáil agus soláthraímid na sonraí bunaidh ionas gur féidir an comparáid a dhéanamh:

```pycon
>>> f = ContactForm(request.POST, initial=data)
>>> f.has_changed()
True
```

Beidh ```has_modified () ``True``` má tá na sonraí ó Request.post\` difriúil ón méid a cuireadh ar fáil in:attr: ~form.initial nó `False` ar shlí eile. Déantar an toradh a ríomh trí ghlaoch: meth: field.has\_changed do gach réimse san fhoirm.

#### `Form.changed_data`

Tugann an tréith `changed_data` liosta d'ainmneacha na réimsí a bhfuil a luachanna i sonraí ceangailte na foirme (request.post\` de ghnáth) difriúil ón méid a cuireadh ar fáil in:attr: ~form.initial. Tugann sé liosta folamh ar ais mura bhfuil aon sonraí difriúil.

```pycon
>>> f = ContactForm(request.POST, initial=data)
>>> f.changed_data
['subject', 'message']
```

## Rochtain a fháil ar na réimsí ón bhfoirm

#### `Form.fields`

Is féidir leat rochtain a fháil ar na réimsí de:class: Form ón tréith `fields`:

```pycon
>>> for row in f.fields.values():
...     print(row)
...
<django.forms.fields.CharField object at 0x7ffaac632510>
<django.forms.fields.URLField object at 0x7ffaac632f90>
<django.forms.fields.CharField object at 0x7ffaac3aa050>
>>> f.fields["name"]
<django.forms.fields.CharField object at 0x7ffaac6324d0>
```

Is féidir leat an réimse agus:class: .BoundField den sampla: Class: Form a athrú chun an bealach a chuirtear i láthair sa fhoirm a athrú:

```pycon
>>> f.as_div().split("</div>")[0]
'<div><label for="id_subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="id_subject">'
>>> f["subject"].label = "Topic"
>>> f.as_div().split("</div>")[0]
'<div><label for="id_subject">Topic:</label><input type="text" name="subject" maxlength="100" required id="id_subject">'
```

Bí cúramach gan an tréith `base_fields` a athrú toisc go mbeidh tionchar ag an modhnú seo ar gach cás ContactForm ina dhiaidh sin laistigh den phróiseas Python céanna:

```pycon
>>> f.base_fields["subject"].label_suffix = "?"
>>> another_f = ContactForm(auto_id=False)
>>> another_f.as_div().split("</div>")[0]
'<div><label for="id_subject">Subject?</label><input type="text" name="subject" maxlength="100" required id="id_subject">'
```

## Rochtain a fháil ar shonraí “glan”

#### `Form.cleaned_data`

Tá gach réimse i rang a: “Foirm” freagrach ní amháin as sonraí a bhailíochtú, ach freisin as iad a “ghlanadh” - iad a normalú go formáid chomhsheasmhach. Is gné deas í seo, toisc go gceadaíonn sé sonraí do réimse áirithe a ionchur ar bhealaí éagsúla, agus aschur comhsheasmhach mar thoradh air i gcónaí.

Mar shampla, normalaíonn :class: ~django.forms.dateField ionchur isteach i réad Python `datetime.date`. Is cuma má chuireann tú sreang air san fhormáid ```'1994-07-15'`, réad ``datetime.date ``, nó roinnt formáidí eile, normalóidh ``DateField``` é i gcónaí go réad datetime.\`date\` fad is atá sé bailí.

Nuair a bheidh sampla a:class: ~Form cruthaithe agat le sraith sonraí agus é a bhailíochtú, is féidir leat rochtain a fháil ar na sonraí glan trína tréith \`\`cleaned\_data\`:

```pycon
>>> data = {
...     "subject": "hello",
...     "message": "Hi there",
...     "contact_email": "foo@example.com",
...     "urgent": True,
... }
>>> f = ContactForm(data)
>>> f.is_valid()
True
>>> f.cleaned_data
{'subject': 'hello', 'message': 'Hi there', 'contact_email': 'foo@example.com', 'urgent': True}
```

Tabhair faoi deara go nglanann aon réimse téacs-bhunaithe - mar `Charfield` nó `Emailfield` \- an t-ionchur i sreang i gcónaí. Clúdóimid na himpleachtaí ionchódú níos déanaí sa doiciméad seo.

Mura ndéantar do chuid sonraí a bhailíochtú, níl ach na réimsí bailí sa fhoclóir cleaned\_data :

```pycon
>>> data = {
...     "subject": "",
...     "message": "Hi there",
...     "contact_email": "invalid email address",
...     "urgent": True,
... }
>>> f = ContactForm(data)
>>> f.is_valid()
False
>>> f.cleaned_data
{'message': 'Hi there', 'urgent': True}
```

Beidh eochair le haghaidh réimsí a shainmhínítear sa `Foirm` i gcónaí\* sa cleaned\_data\`, fiú má chuireann tú sonraí breise nuair a shainmhíníonn tú an `Foirm`. Sa sampla seo, cuirimid dornán réimsí breise chuig an tógálaí ContactForm \`, ach níl ach réimsí na foirme sa cleaned\_data\`:

```pycon
>>> data = {
...     "subject": "hello",
...     "message": "Hi there",
...     "contact_email": "foo@example.com",
...     "urgent": True,
...     "extra_field_1": "foo",
...     "extra_field_2": "bar",
...     "extra_field_3": "baz",
... }
>>> f = ContactForm(data)
>>> f.is_valid()
True
>>> f.cleaned_data  # Doesn't contain extra_field_1, etc.
{'subject': 'hello', 'message': 'Hi there', 'contact_email': 'foo@example.com', 'urgent': True}
```

When the `Form` is valid, `cleaned_data` will include a key and value for
*all* its fields, even if the data didn't include a value for some optional
fields. In this example, the data dictionary doesn't include a value for the
`nickname` field, but `cleaned_data` includes it, with an empty value:

```pycon
>>> from django import forms
>>> class OptionalPersonForm(forms.Form):
...     first_name = forms.CharField()
...     last_name = forms.CharField()
...     nickname = forms.CharField(required=False)
...
>>> data = {"first_name": "John", "last_name": "Lennon"}
>>> f = OptionalPersonForm(data)
>>> f.is_valid()
True
>>> f.cleaned_data
{'first_name': 'John', 'last_name': 'Lennon', 'nickname': ''}
```

In this above example, the `cleaned_data` value for `nickname` is set to
an empty string, because `nickname` is `CharField`, and `CharField`s
treat empty values as an empty string. Each field type knows what its "blank"
value is -- e.g., for `DateField`, it's `None` instead of the empty string.
For full details on each field's behavior in this case, see the "Empty value"
note for each field in the [Ranganna \`\`Réimse \`\`tógtha](/ga/6.0/ref/forms/fields/#built-in-fields) section below.

Is féidir leat cód a scríobh chun bailíochtú a dhéanamh do réimsí foirme áirithe (bunaithe ar a n-ainm) nó don fhoirm ina iomláine (ag smaoineamh ar theaglaim de réimsí éagsúla). Tá tuilleadh faisnéise faoi seo in:doc: /ref/forms/validation.

## Foirmeacha a chur amach mar HTML

Is é an dara tasc atá ag réad `Foirm` é féin a rinneadh mar HTML. Chun é sin a dhéanamh, `print` é:

```pycon
>>> f = ContactForm()
>>> print(f)
<div><label for="id_subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="id_subject"></div>
<div><label for="id_message">Message:</label><textarea name="message" cols="40" rows="10" required id="id_message"></textarea></div>
<div><label for="id_contact_email">Contact email:</label><input type="email" name="contact_email" maxlength="320" required id="id_contact_email"></div>
<div><label for="id_urgent">Urgent:</label><input type="checkbox" name="urgent" id="id_urgent"></div>
```

Má tá an fhoirm ceangailte le sonraí, cuirfear na sonraí sin san áireamh go cuí san aschur HTML. Mar shampla, má léirítear réimse le `<input type="text">`, beidh na sonraí sa tréith `luach`. Má léirítear réimse le ``` `, ansin cuir <input type="checkbox">fidh an HTML sin ``seiceáil ``` más cuí:

```pycon
>>> data = {
...     "subject": "hello",
...     "message": "Hi there",
...     "contact_email": "foo@example.com",
...     "urgent": True,
... }
>>> f = ContactForm(data)
>>> print(f)
<div><label for="id_subject">Subject:</label><input type="text" name="subject" value="hello" maxlength="100" required id="id_subject"></div>
<div><label for="id_message">Message:</label><textarea name="message" cols="40" rows="10" required id="id_message">Hi there</textarea></div>
<div><label for="id_contact_email">Contact email:</label><input type="email" name="contact_email" value="foo@example.com" maxlength="320" required id="id_contact_email"></div>
<div><label for="id_urgent">Urgent:</label><input type="checkbox" name="urgent" id="id_urgent" checked></div>
```

\<div\>Cumhdaíonn an t-aschur réamhshocraithe seo gach réimse le . Tabhair faoi deara a leanas:

- \<input type="submit"\>Maidir le solúbthacht, ní chuimsíonn an aschuir\* na clibeanna \`\` \<form\>agus \`\` `nó clib</form>` . Is é do phost é sin a dhéanamh.
- Tá ionadaíocht HTML réamhshocraithe ag gach cineál réimse. \<input type="email"\>Léirítear `charfield` le \`\` ```agus ``Ríomhphost``` le\`\` \`\` \`\` \`\` \`\` `` ` `` \`\` \`\` \<input type="text"\>\`\`\`\` \<input type="checkbox"\>Léirítear ``` `BooleanField (Null=bréagach) ``le ``` . Tabhair faoi deara nach bhfuil siad seo ach réamhshocruithe ciallmhara; is féidir leat a shonrú cén HTML atá le húsáid do réimse ar leith trí ghuirléidí a úsáid, a mhíneoimid go luath.
- Tógtar an ```ainm ``HTML do gach clib go díreach óna ainm tréithe sa rang ``Contactform```.
- The text label for each field -- e.g. `'Subject:'`, `'Message:'` and
  `'Contact email:'` is generated from the field name by converting all
  underscores to spaces and upper-casing the first letter. Again, note
  these are merely sensible defaults; you can also specify labels manually.
- Tá gach lipéad téacs timpeallaithe i gclib HTML `<label>`, a chuireann in iúl don réimse foirme iomchuí trína id \`. Gintear a id\`, ina dhiaidh sin, trí `id_'` a réamhfheidhmiú chuig ainm an réimse. Cuirtear na tréithe id\` agus na clibeanna `<label>` san áireamh san aschur de réir réamhshocraithe, chun dea-chleachtais a leanúint, ach is féidir leat an t-iompar sin a athrú.
- Úsáideann an t-aschur comhréir HTML5, ag díriú ar `<DOCTYPE html>`. Mar shampla, úsáideann sé tréithe boolean mar `checked` seachas an stíl XHTML de checked='checked'.

Cé gurb é as \<div\>chur `` `an stíl aschuir réamhshocraithe nuair a dhéanann tú foirm `` a phriontáil is féidir leat an t-aschur a shaincheapadh trí do theimpléad foirme féin a úsáid ar féidir a shocrú ar fud an láithreáin, in aghaidh foirme, nó in aghaidh na sampla. Féach:ref: teimpléid foirm-athúsáid'.

### Rindreáil réamhshocrai

Úsáideann an rindreáil réamhshocraithe nuair a dhéanann tú foirm “priontáil” na modhanna agus na tréithe seo a leanas.

#### `ainmne_teimpléad`

#### `Form.template_name`

Ainm an teimpléid a rinneadh má theilgtear an fhoirm isteach i sreang, m.sh. trí ```priontáil (foirm) ``nó i dteimpléad trí``` {{form}} .

De réir réamhshocraithe, maoin ag filleadh luach an renderer's:attr: ~django.forms.renderers.baserenderer.form\_template\_name. Féadfaidh tú é a shocrú mar ainm teimpléad teaghrán d'fhonn é sin a shárú d'aicme foirme áirithe.

#### render () \`\`

#### `Form.render(template_name=None, context=None, renderer=None)`

Tugtar `__str__` ar an modh rindreála chomh maith leis na:meth: .form.as\_div, :meth: .form.as\_table, :meth: .form.as\_p, agus:meth: .form.as\_ul modhanna. Tá gach argóint roghnach agus réamhshocraithe:

- `ainm_teimpléad`: :attr: .form.template\_ainm
- `context`: Luach ar ais ag: meth: .form.get\_context
- `renderer`: Luach ar ais ar:attr: .form.default\_renderer

Trí `template_name` a rith is féidir leat an teimpléad a úsáidtear le haghaidh glao amháin a shaincheapadh.

#### get\_context () \`\`

#### `Form.get_context()`

Tabhair ar ais an gcomhthéacs teimpléid chun an fhoirm a rin

Is é an comhthéacs atá ar fáil:

- `foirm`: An fhoirm cheangailte.
- `fields`: Gach réimse ceangailte, seachas na réimsí i bhfolach.
- `hidden_fields`: Gach réimse ceangailte i bhfolach.
- earráidí : Gach earráid foirme neamh-bhaineann le réimse nó i bhfolach a bhaineann le réimse.

#### `teimpléad_ainm_lipéad`

#### `Form.template_name_label`

An teimpléad a úsáidtear chun réimse a léiriú\<label\>, a úsáidtear nuair a ghlaoitear: meth: \`BoundField.label\_tag/:Meth: ~BoundField.LEGEND\_TAG. Is féidir é a athrú in aghaidh an fhoirme tríd an tréith seo a shárú nó níos ginearálta tríd an teimpléad réamhshocraithe a shárú, féach freis:ref: overriding-built-in-form-templates.

### Stíleanna aschuir

Is é an cur chuige a mholtar chun stíl aschuir foirme a athrú ná teimpléad foirme saincheaptha a shocrú ar fud an láithreáin, in aghaidh na foirme, nó in aghaidh an Féach:ref: reusable-form-templates le haghaidh samplaí.

Cuirtear na feidhmeanna cúntóra seo a leanas ar fáil le haghaidh comhoiriúnacht ar chúl agus is seachfhreastalaí iad chuig:meth: Form.render ag rith luach áirithe `template_name`.

> **Note**
>
> \<fieldset\>\<legend\>As an chreat teimpléid agus stíleanna aschuir a sholáthraítear, moltar an réamhshocraithe ```as_div () ``thar na leaganacha ``as_p ()```, as\_table () \`, agus `as_ul ()` mar a chuireann an teimpléad \`\` agus \`\` i bhfeidhm ar ionchuir gaolmhara agus tá sé níos éasca d'úsáideoirí léitheoirí scáileáin nascleanúint a dhéanamh.

Déanann gach cúntóir modh foirme le tréith a thugann an t-ainm teimpléid chuí.

#### as\_div () \`\`

#### `Form.template_name_div`

An teimpléad a úsáideann ````as_div () ``. Réamhshocraithe: ```django/forms/div.html'````.

#### `Form.as_div()`

\<div\>Léiríonn ```as_div () ``an fhoirm mar shraith eilimintí``` `, agus réimse amháin i ng <div>ach` , mar shampla:

```pycon
>>> f = ContactForm()
>>> f.as_div()
```

... gives HTML like:

```html
<div>
<label for="id_subject">Subject:</label>
<input type="text" name="subject" maxlength="100" required id="id_subject">
</div>
<div>
<label for="id_message">Message:</label>
<textarea name="message" cols="40" rows="10" required id="id_message"></textarea>
</div>
<div>
<label for="id_contact_email">Contact email:</label>
<input type="email" name="contact_email" required id="id_contact_email">
</div>
<div>
<label for="id_urgent">Urgent:</label>
<input type="checkbox" name="urgent" id="id_urgent">
</div>
```

#### as\_p () \`\`

#### `Form.template_name_p`

An teimpléad a úsáideann ````as_p () ``. Réamhshocraithe: ```django/forms/p.html'````.

#### `Form.as_p()`

\<p\>Léiríonn ```as_p () ``an fhoirm mar shraith clibeanna``` `, agus réimse amháin i <p>ngach` :

```pycon
>>> f = ContactForm()
>>> f.as_p()
```

... gives HTML like:

```html
<p><label for="id_subject">Subject:</label> <input type="text" name="subject" maxlength="100" required id="id_subject"></p>
<p><label for="id_message">Message:</label> <textarea name="message" cols="40" rows="10" required id="id_message"></textarea></p>
<p><label for="id_contact_email">Contact email:</label> <input type="email" name="contact_email" maxlength="320" required id="id_contact_email"></p>
<p><label for="id_urgent">Urgent:</label> <input type="checkbox" name="urgent" id="id_urgent"></p>
```

#### as\_ul () \`\`

#### `Form.template_name_ul`

An teimpléad a úsáideann ````as_ul () ``. Réamhshocraithe: ```django/forms/ul.html'````.

#### `Form.as_ul()`

\<li\>Léiríonn ```as_ul () ``an fhoirm mar shraith clibeanna``` `<li>, agus réimse amháin i ngach` ``` . <ul>Cuimsíonn ai*ní* an `` ``` nó `<ul>`, ionas gur féidir leat aon tréithe HTML a shonrú ar\</ul\> an \`\` le haghaidh solúbthachta:

```pycon
>>> f = ContactForm()
>>> f.as_ul()
```

... gives HTML like:

```html
<li><label for="id_subject">Subject:</label> <input type="text" name="subject" maxlength="100" required id="id_subject"></li>
<li><label for="id_message">Message:</label> <textarea name="message" cols="40" rows="10" required id="id_message"></textarea></li>
<li><label for="id_contact_email">Contact email:</label> <input type="email" name="contact_email" maxlength="320" required id="id_contact_email"></li>
<li><label for="id_urgent">Urgent:</label> <input type="checkbox" name="urgent" id="id_urgent"></li>
```

#### as\_table () \`\`

#### `Form.template_name_table`

An teimpléad a úsáideann ````as_table () ``. Réamhshocraithe: ```django/forms/table.html'````.

#### `Form.as_table()`

\<table\>Léiríonn ```as_table () ``an fhoirm mar HTML``` :

```pycon
>>> f = ContactForm()
>>> f.as_table()
```

... gives HTML like:

```html
<tr><th><label for="id_subject">Subject:</label></th><td><input type="text" name="subject" maxlength="100" required id="id_subject"></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><textarea name="message" cols="40" rows="10" required id="id_message"></textarea></td></tr>
<tr><th><label for="id_contact_email">Contact email:</label></th><td><input type="email" name="contact_email" maxlength="320" required id="id_contact_email"></td></tr>
<tr><th><label for="id_urgent">Urgent:</label></th><td><input type="checkbox" name="urgent" id="id_urgent"></td></tr>
```

### Stíliú riachtanacha nó sraitheanna foir

#### `Form.error_css_class`

#### `Form.required_css_class`

Tá sé coitianta go leor sraitheanna agus réimsí a fhoirmiú atá ag teastáil nó a bhfuil earráidí acu. Mar shampla, b'fhéidir gur mhaith leat na sraitheanna foirme riachtanacha a chur i láthair i dtrom agus earráidí a aibhsiú

Tá cúpla crúca ag an rang:class: Form is féidir leat a úsáid chun tréithe `class` a chur leis na sraitheanna riachtanacha nó le sraitheanna le hearráidí: socraigh na tréithe: attr: Form.error\_css\_class agus/nó :attr: Form.required\_css\_class tréithe:

```
from django import forms

class ContactForm(forms.Form):
    error_css_class = "error"
    required_css_class = "required"

    # ... and the rest of your fields here
```

Nuair a bheidh sé sin déanta agat, tabharfar ranganna `"earráid"` agus/nó `"riachtana"` sraitheanna, de réir mar is gá. Beidh cuma ar an HTML rud éigin cosúil le:

```pycon
>>> f = ContactForm(data)
>>> print(f)
<div class="required"><label for="id_subject" class="required">Subject:</label> ...
<div class="required"><label for="id_message" class="required">Message:</label> ...
<div class="required"><label for="id_contact_email" class="required">Contact email:</label> ...
<div><label for="id_urgent">Urgent:</label> ...
>>> f["subject"].label_tag()
<label class="required" for="id_subject">Subject:</label>
>>> f["subject"].legend_tag()
<legend class="required" for="id_subject">Subject:</legend>
>>> f["subject"].label_tag(attrs={"class": "foo"})
<label for="id_subject" class="foo required">Subject:</label>
>>> f["subject"].legend_tag(attrs={"class": "foo"})
<legend for="id_subject" class="foo required">Subject:</legend>
```

You may further modify the rendering of form rows by using a
[custom BoundField](#custom-boundfield).

### \<label\>Eilimintí foirme a chumrú tréithe 'HTML `id` agus clibeanna

#### `Form.auto_id`

De réir réamhshocraithe, tá na modhanna rindreála foirme tá:

- Tréithe HTML id ar na heilimintí foirme.
- Na clibeanna comhfhreagracha \<label\>\`\`\`timpeall na lipéid. Ainmníonn clib HTML \<label\>\`\`\`cén téacs lipéad a bhaineann leis an eilimint foirme. Déanann an feabhsú beag seo foirmeacha níos inúsáidte agus níos inrochtana do ghléasanna cúnta. Is smaoineamh maith é i gcónaí clibeanna \<label\>\`\`\`a úsáid.

The `id` attribute values are generated by prepending `id_` to the form
field names. This behavior is configurable, though, if you want to change the
`id` convention or remove HTML `id` attributes and `<label>` tags
entirely.

Úsáid an argóint `auto_id` chuig an tógálaí ```Form ``chun an `id``` agus an iompar lipéad a rialú. Caithfidh an argóint seo a bheith `True`, Fréag\` nó teaghrán.

\<label\>Más é `auto_id` False\`, ansin ní bheidh clibeanna \`\` ná tréithe id san áireamh sa aschur foirme:

```pycon
>>> f = ContactForm(auto_id=False)
>>> print(f)
<div>Subject:<input type="text" name="subject" maxlength="100" required></div>
<div>Message:<textarea name="message" cols="40" rows="10" required></textarea></div>
<div>Contact email:<input type="email" name="contact_email" required></div>
<div>Urgent:<input type="checkbox" name="urgent"></div>
```

Má tá `auto_id` socraithe go `True`, ansin cuirfear clibeanna \`\` san aschur foirme\*\* agus úsáidfidh sé ainm an réimse mar a id \<label\>\`\`do gach réimse foirme:

```pycon
>>> f = ContactForm(auto_id=True)
>>> print(f)
<div><label for="subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="subject"></div>
<div><label for="message">Message:</label><textarea name="message" cols="40" rows="10" required id="message"></textarea></div>
<div><label for="contact_email">Contact email:</label><input type="email" name="contact_email" required id="contact_email"></div>
<div><label for="urgent">Urgent:</label><input type="checkbox" name="urgent" id="urgent"></div>
```

Má tá `auto_id` socraithe ar shreang ina bhfuil an carachtar formáide `` `%s' ``, ansin beidh clibeanna \`\` san aschur foirme, agus ginfidh sé tréithe ````id <label>``bunaithe ar an teaghrán formáide. Mar shampla, i gcás teaghrán formáide ```field_%s'````, gheobhaidh réimse darb ainm `` `subject `` an luach `id` `` `field_subject' ``. Leanúint lenár sampla:

```pycon
>>> f = ContactForm(auto_id="id_for_%s")
>>> print(f)
<div><label for="id_for_subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="id_for_subject"></div>
<div><label for="id_for_message">Message:</label><textarea name="message" cols="40" rows="10" required id="id_for_message"></textarea></div>
<div><label for="id_for_contact_email">Contact email:</label><input type="email" name="contact_email" required id="id_for_contact_email"></div>
<div><label for="id_for_urgent">Urgent:</label><input type="checkbox" name="urgent" id="id_for_urgent"></div>
```

Má tá auto\_id\` socraithe ar aon luach fíor eile -- mar shampla sreang nach bhfuil `%s` san áireamh -- ansin gníomhóidh an leabharlann amhail is dá mbeidh `auto_id` `True`.

De réir réamhshocraithe, socraítear `auto_id` go dtí an teaghrán `'id_%s'`.

#### `Form.label_suffix`

Sreang inaistrithe (réamhshocraithe go colon (`:`) i mBéarla) a chuirfear isteach i ndiaidh aon ainm lipéad nuair a dhéantar foirm a léiriú.

Is féidir an carachtar sin a shaincheapadh, nó é a fhágáil go hiomlán, ag baint úsáide as an paraiméadar label\_suffix\`:

```pycon
>>> f = ContactForm(auto_id="id_for_%s", label_suffix="")
>>> print(f)
<div><label for="id_for_subject">Subject</label><input type="text" name="subject" maxlength="100" required id="id_for_subject"></div>
<div><label for="id_for_message">Message</label><textarea name="message" cols="40" rows="10" required id="id_for_message"></textarea></div>
<div><label for="id_for_contact_email">Contact email</label><input type="email" name="contact_email" required id="id_for_contact_email"></div>
<div><label for="id_for_urgent">Urgent</label><input type="checkbox" name="urgent" id="id_for_urgent"></div>
>>> f = ContactForm(auto_id="id_for_%s", label_suffix=" ->")
>>> print(f)
<div><label for="id_for_subject">Subject -&gt;</label><input type="text" name="subject" maxlength="100" required id="id_for_subject"></div>
<div><label for="id_for_message">Message -&gt;</label><textarea name="message" cols="40" rows="10" required id="id_for_message"></textarea></div>
<div><label for="id_for_contact_email">Contact email -&gt;</label><input type="email" name="contact_email" required id="id_for_contact_email"></div>
<div><label for="id_for_urgent">Urgent -&gt;</label><input type="checkbox" name="urgent" id="id_for_urgent"></div>
```

Tabhair faoi deara nach gcuirtear iarmhír an lipéad leis ach mura carachtar poncaíochta é an carachtar deireanach den lipéad (i mBéarla, is iad sin `.`, ```! ``,```? `nó`: ).

Is féidir le réimsí a gcuid féin a shainiú freisin: attr: ~django.forms.field.label\_suffix. \<django.forms.Form.label\_suffix\>Beidh tosaíocht aige seo thair:attr: form.label\_suffix \`. Is féidir an iarmhír a shárú freisin ag rith ag baint úsáide as an paraiméadar \`\`label\_suffix\` to:meth: ~django.forms.boundfield.label\_tag/:Meth: ~django.forms.boundfield.legend\_tag.

#### `Form.use_required_attribute`

Nuair a bheidh sé socraithe go `True` (an réamhshocraithe), beidh an tréith HTML `riachtanaithe` ag réimsí foirme riachtanacha.

[Formsets](/ga/6.0/topics/forms/formsets/) instantiate forms with
`use_required_attribute=False` to avoid incorrect browser validation when
adding and deleting forms from a formset.

### Rindreáil giuirléidí foirme a chumrú

#### `Form.default_renderer`

Specifies the [renderer](/ga/6.0/ref/forms/renderers/) to use for the form.
Defaults to `None` which means to use the default renderer specified by the
[`FORM_RENDERER`](/ga/6.0/ref/settings/#std-setting-FORM_RENDERER) setting.

Is féidir leat é seo a shocrú mar thréith aicme agus tú ag dearbhú d'fhoirm nó an argóint `renderer` a úsáid chuig Foirm. \_\_init\_\_ () \`. Mar shampla:

```
from django import forms

class MyForm(forms.Form):
    default_renderer = MyRenderer()
```

nó:

```
form = MyForm(renderer=MyRenderer())
```

### Nótaí ar ordú allamuigh

In the `as_p()`, `as_ul()` and `as_table()` shortcuts, the fields are
displayed in the order in which you define them in your form class. For
example, in the `ContactForm` example, the fields are defined in the order
`subject`, `message`, `contact_email`, `urgent`. To reorder the HTML
output, change the order in which those fields are listed in the class.

Tá roinnt bealaí eile ann chun an t-ordú a shaincheapadh:

#### `Form.field_order`

De réir réamhshocraithe `form.field_order=None`, a choimeádann an t-ord ina sainmhíníonn tú na réimsí i do rang foirme. Más liosta d'ainmneacha réimsí é field\_order\`, ordaítear na réimsí mar a shonraíonn an liosta agus cuirtear réimsí eile leis an ordú réamhshocraithe. Déantar neamhaird ar ainmneacha réimse anaithnid sa liosta Fágann sé seo gur féidir réimse i bhfo-aicme a dhíchumasú tríd é a shocrú go None gan ordú a athshainiú.

Is féidir leat an argóint `Form.field_Order` a úsáid chuig a:class: Form chun an t-ordú réimse a shárú. Má shainmhíníonn a:class: ~django.forms.form: attr: ~form.field\_order *agus* chuimsíonn tú `field_order` nuair a chuirtear an Form\` i bhfeidhm, ansin beidh tosaíocht ag an field\_ord\` deireanach.

#### `Form.order_fields(field_order)`

Féadfaidh tú na réimsí a athshocrú am ar bith ag baint úsáide as order\_fields () le liosta ainmneacha réimse mar atá in:attr: ~django.forms.form.field\_order.

### Conas a thaispeántar earráidí

If you render a bound `Form` object, the act of rendering will automatically
run the form's validation if it hasn't already happened, and the HTML output
will include the validation errors as a `<ul class="errorlist">`.

The following:

```pycon
>>> data = {
...     "subject": "",
...     "message": "Hi there",
...     "contact_email": "invalid email address",
...     "urgent": True,
... }
>>> ContactForm(data).as_div()
```

... gives HTML like:

```html
<div>
  <label for="id_subject">Subject:</label>
  <ul class="errorlist" id="id_subject_error"><li>This field is required.</li></ul>
  <input type="text" name="subject" maxlength="100" required aria-invalid="true" aria-describedby="id_subject_error" id="id_subject">
</div>
<div>
  <label for="id_message">Message:</label>
  <textarea name="message" cols="40" rows="10" required id="id_message">Hi there</textarea>
</div>
<div>
  <label for="id_contact_email">Contact email:</label>
  <ul class="errorlist" id="id_contact_email_error"><li>Enter a valid email address.</li></ul>
  <input type="email" name="contact_email" value="invalid email address" maxlength="320" required aria-invalid="true" aria-describedby="id_contact_email_error" id="id_contact_email">
</div>
<div>
    <label for="id_urgent">Urgent:</label>
    <input type="checkbox" name="urgent" id="id_urgent" checked>
</div>
```

Django's default form templates will associate validation errors with their
input by using the `aria-describedby` HTML attribute when the field has an
`auto_id` and a custom `aria-describedby` is not provided. If a custom
`aria-describedby` is set when defining the widget this will override the
default value.

If the widget is rendered in a `<fieldset>` then `aria-describedby` is
added to this element, otherwise it is added to the widget's HTML element (e.g.
`<input>`).

> **Changed in Django 5.2**
>
> `aria-describedby` was added to associate errors with its input.

### Formáid an liosta earráide a shaincheapadh

#### `class ErrorList(initlist=None, error_class=None, renderer=None, field_id=None)`

De réir réamhshocraithe, úsáideann foirmeacha `Django.Forms.Utils.ErrorList` chun earráidí bailíochtaithe a fhormáidiú. Is liosta cosúil le réad é `ErrorList` ina bhfuil `initlist` liosta na n-earráidí. Ina theannta sin tá na tréithe agus na modhanna seo a leanas ag an rang seo a leanas.

> **Changed in Django 5.2**
>
> The `field_id` argument was added.

#### `error_class`

Na ranganna CSS le húsáid agus an liosta earráide á rindreáil. Cuirtear aon ranganna a chuirtear ar fáil leis an rang réamhshocraithe `earrlista`.

#### `renderer`

Specifies the [renderer](/ga/6.0/ref/forms/renderers/) to use for
`ErrorList`. Defaults to `None` which means to use the default
renderer specified by the [`FORM_RENDERER`](/ga/6.0/ref/settings/#std-setting-FORM_RENDERER) setting.

#### `field_id`

> **New in Django 5.2**

An `id` for the field for which the errors relate. This allows an
HTML `id` attribute to be added in the error template and is useful
to associate the errors with the field. The default template uses the
format `id="{{ field_id }}_error"` and a value is provided by
[`Form.add_error()`](#django.forms.Form.add_error) using the field's [`auto_id`](#django.forms.BoundField.auto_id).

#### `template_name`

Ainm an teimpléid a úsáidtear agus tú ag glaoch ar `__str__` nó:meth: render. De réir réamhshocraithe is é seo `django/forms/errors/list/default.html'` atá ina seachfhreastalaí don teimpléad `` `ul.html' ``.

#### `template_name_text`

Ainm an teimpléid a úsáidtear agus tú ag glaoch: meth: .as\_text. De réir réamhshocraithe is é seo `django/forms/errors/list/text.html'`. Déanann an teimpléad seo na hearráidí mar liosta de phointí piléar.

#### `template_name_ul`

Ainm an teimpléid a úsáidtear agus tú ag glaoch: meth: .as\_ul. De réir réamhshocraithe is é seo `django/forms/errors/list/ul.html'`. Déanann an teimpléad seo na hearráidí i gclibeanna `` `le timfhilleadh<li> `` leis na ranganna \<ul\>CSS mar a shainmhínítear ar:attr: .error\_class.

#### `get_context()`

Comhthéacs ar ais chun earráidí a rindreáil i dteimpléad.

Is é an comhthéacs atá ar fáil:

- earráidí : Liosta de na hearráidí.
- `error_class`: Sraith ranganna CSS.

#### `render(template_name=None, context=None, renderer=None)`

Tugtar `__str__` ar an modh rindreála chomh maith leis an modh:meth: .as\_ul.

Tá na hargóintí go léir roghnach agus beidh siad réamhshocraithe:

- `template_name`: Luach ar ais ag: attr: .template\_name
- `context`: Luach ar ais ag: meth: .get\_context
- `renderer`: Luach ar ais ar:attr: .renderer

#### `as_text()`

Déanann sé an liosta earráide ag baint úsáide as an teimpléad atá sainmhínithe ar:attr: .template\_name\_text.

#### `as_ul()`

Déanann sé an liosta earráide ag baint úsáide as an teimpléad atá sainmhínithe ar:attr: .template\_name\_ul.

Más mian leat rindreáil earráidí a shaincheapadh is féidir é seo a bhaint amach tríd an tréith: attr: .template\_name a shárú nó níos ginearálta tríd an teimpléad réamhshocraithe a shárú, féach freis:ref: overriding-built-in-form-templates.

## Níos mó aschur gráinneach

Is aicearraí iad na modhanna ```as_p () ``, `as_ul ()```, agus as\_table () \- ní hé sin an t-aon bhealach is féidir réad foirme a thaispeáint.

#### `class BoundField`

Úsáidtear chun tréithe HTML nó rochtana a thaispeáint do réimse amháin de shampla a:class: Form.

Taispeánann modh \_\_str\_\_ () an réada seo an HTML don réimse seo.

You can use [`Form.bound_field_class`](#django.forms.Form.bound_field_class) and
[`Field.bound_field_class`](/ga/6.0/ref/forms/fields/#django.forms.Field.bound_field_class) to specify a different `BoundField` class
per form or per field, respectively.

See [Saincheapadh Boundfield](#custom-boundfield) for examples of overriding a `BoundField`.

Chun Boundfield\` amháin a aisghabháil, bain úsáid as comhréiteach cuardaigh foclóra ar d'fhoirm ag baint úsáide as ainm an réimse mar eochair:

```pycon
>>> form = ContactForm()
>>> print(form["subject"])
<input type="text" name="subject" maxlength="100" required id="id_subject">
```

Chun gach rud Boundfield\` a aisghabháil, athraigh an fhoirm:

```pycon
>>> form = ContactForm()
>>> for boundfield in form:
...     print(boundfield)
...
<input type="text" name="subject" maxlength="100" required id="id_subject">
<textarea name="message" cols="40" rows="10" required id="id_message"></textarea>
<input type="email" name="contact_email" maxlength="320" required id="id_contact_email">
<input type="checkbox" name="urgent" id="id_urgent">
```

Tugann an t-aschur réimsi-shonrach onóir socrú `auto_id` réad foirme:

```pycon
>>> f = ContactForm(auto_id=False)
>>> print(f["message"])
<textarea name="message" cols="40" rows="10" required></textarea>
>>> f = ContactForm(auto_id="id_%s")
>>> print(f["message"])
<textarea name="message" cols="40" rows="10" required id="id_message"></textarea>
```

### Tréithe `Boundfield`

#### `BoundField.aria_describedby`

> **New in Django 5.2**

Returns an `aria-describedby` reference to associate a field with its
help text and errors. Returns `None` if `aria-describedby` is set in
[`Widget.attrs`](/ga/6.0/ref/forms/widgets/#django.forms.Widget.attrs) to preserve the user defined attribute when rendering
the form.

#### `BoundField.auto_id`

An tréith ID HTML don BoundField\` seo. Tugann teaghrán folamh ar ais má tá: attr: Form.auto\_id `False`.

#### `BoundField.data`

Tugann an maoin seo na sonraí don seo: class: ~django.forms.BoundField a bhaintear ag an modh giuirléid 's:meth: ~django.forms.widget.value\_from\_datadict, nó `None` mura dtugadh é:

```pycon
>>> unbound_form = ContactForm()
>>> print(unbound_form["subject"].data)
None
>>> bound_form = ContactForm(data={"subject": "My Subject"})
>>> print(bound_form["subject"].data)
My Subject
```

#### `BoundField.errors`

\<ul class="errorlist"\>A: Ref: réad cosúil le liosta \<ref-forms-error-list-format\>\`a thaispeántar mar HTML \`\` nuair a bheidh clóite:

```pycon
>>> data = {"subject": "hi", "message": "", "contact_email": "", "urgent": ""}
>>> f = ContactForm(data, auto_id=False)
>>> print(f["message"])
<input type="text" name="message" required aria-invalid="true">
>>> f["message"].errors
['This field is required.']
>>> print(f["message"].errors)
<ul class="errorlist"><li>This field is required.</li></ul>
>>> f["subject"].errors
[]
>>> print(f["subject"].errors)

>>> str(f["subject"].errors)
''
```

Agus réimse á rindreáil le hearráidí, socraítear `aria-invalid="true"` ar ghuirléid an réimse chun a léiriú go bhfuil earráid ann d'úsáideoirí léitheoirí scáileáin.

#### `BoundField.field`

An sampla foirm:class: ~django.forms.field ón rang foirm a fhilleann seo:class: ~django.forms.boundfield.

#### `BoundField.form`

Tá an sampla:Class: ~django.forms.form ceangailte leis seo: class: ~Django.Forms.BoundField.

#### `BoundField.help_text`

An: attr: ~django.forms.field.help\_text an réimse.

#### `BoundField.html_name`

An t-ainm a úsáidfear i dtréith HTML ainm an ghuirléid. Cuireann sé an fhoirm: attr: ~django.forms.form.prefix san áireamh.

#### `BoundField.id_for_label`

Úsáid an maoin seo chun aitheantas an réimse seo a léiriú. Mar shampla, má tá á thógáil de láimh agat i do the \<label\>impléad (in ainneoin go ndéanfaidh: meth: \`~BoundField.label\_tag/:Meth: ~BoundField.Legend\_Tag é seo duit):

```html+django
<label for="{{ form.my_field.id_for_label }}">...</label>{{ my_field }}
```

De réir réamhshocraithe, is é seo ainm an réimse réamhshocraithe le `id_` (“id\_my\_field\`” don sampla thuas). Féadfaidh tú an ID a mhodhnú trí:attr: ~django.forms.widget.attrs ar ghuirléid an réimse. Mar shampla, réimse mar seo a dhearbhú:

```
my_field = forms.CharField(widget=forms.TextInput(attrs={"id": "myFIELD"}))
```

agus ag baint úsáide as an teimpléad thuas, déanfaí rud éigin mar:

```html
<label for="myFIELD">...</label><input id="myFIELD" type="text" name="my_field" required>
```

#### `BoundField.initial`

Úsáid: attr: BoundField.initial chun sonraí tosaigh a aisghabháil do réimse foirme. Aisghabhann sé na sonraí ó:attr: Form.initial má tá sé i láthair, ar shlí eile iarracht: attr: Field.initial. Déantar luachanna inghlaonta a mheas. Féach:ref: ref-forms-initial-form-values le haghaidh tuilleadh samplaí.

[`BoundField.initial`](#django.forms.BoundField.initial) caches its return value, which is useful
especially when dealing with callables whose return values can change (e.g.
`datetime.now` or `uuid.uuid4`):

```pycon
>>> from datetime import datetime
>>> class DatedCommentForm(CommentForm):
...     created = forms.DateTimeField(initial=datetime.now)
...
>>> f = DatedCommentForm()
>>> f["created"].initial
datetime.datetime(2021, 7, 27, 9, 5, 54)
>>> f["created"].initial
datetime.datetime(2021, 7, 27, 9, 5, 54)
```

Using [`BoundField.initial`](#django.forms.BoundField.initial) is recommended over
[`get_initial_for_field()`](#django.forms.Form.get_initial_for_field).

#### `BoundField.is_hidden`

Tugann sé ar ais `True` má tá giuirléid seo:class: ~django.forms.BoundField i bhfolach.

#### `BoundField.label`

An: Attr: ~django.forms.field.label an réimse. Úsáidtear é seo in:meth: ~BoundField.label\_tag/:Meth: ~BoundField.LEGEND\_TAG.

#### `BoundField.name`

Ainm an réimse seo sa fhoirm:

```pycon
>>> f = ContactForm()
>>> print(f["subject"].name)
subject
>>> print(f["message"].name)
message
```

#### `BoundField.template_name`

Ainm an teimpléid a rinneadh le:meth: .BoundField.as\_Field\_Group.

Maoin ag tugadh luach an:attr: ~django.forms.field.template\_name má tá sé socraithe ar bhealach eile: attr: ~django.forms.renderers.baserenderer.field\_template\_name.

#### `BoundField.use_fieldset`

Tugann luach tréith `use_fieldset` ghuirléid BoundField seo ar ais.

#### `BoundField.widget_type`

Tugann ainm aicme íseal giuirléid an réimse fillte ar ais, agus baintear aon `input` nó `` giuirléid ` ``. Féadfar é seo a úsáid agus foirmeacha á thógáil ina bhfuil an leagan amach ag brath ar an gcineál giuirléid. Mar shampla:

```html+django
{% for field in form %}
    {% if field.widget_type == 'checkbox' %}
        # render one way
    {% else %}
        # render another way
    {% endif %}
{% endfor %}
```

### Modhanna `Boundfield`

#### `BoundField.as_field_group()`

Déanann sé an réimse ag baint úsáide:meth: .BoundField.render le luachanna réamhshocraithe a thugann an BoundField\`, lena n-áirítear a lipéad, téacs cabhrach agus earráidí ag baint úsáide as an teimpléad's:attr: ~django.forms.renderers.baserender.field.template\_name má shocraítear ar arís eile: attr: ~django.forms.renderers.baserenderer.field.field.field.field.field\_Teimpléad\_ainm

#### `BoundField.as_hidden(attrs=None, **kwargs)`

Tugann sé sreang HTML ar ais chun é seo a léiriú mar \<input type="hidden"\>\`\`\`.

Cuirtear kwargs chuig: meth: ~django.forms.boundfield.as\_widget.

Úsáidtear an modh seo go domhanda go hinmheánach. Ba chóir duit giuirléid a úsáid ina ionad.

#### `BoundField.as_widget(widget=None, attrs=None, only_initial=False)`

Renders the field by rendering the passed widget, adding any HTML
attributes passed as `attrs`. If no widget is specified, then the
field's default widget will be used.

Úsáideann inmheánacha Django `only_initial` agus níor cheart é a shocrú go sainráite.

#### `BoundField.css_classes(extra_classes=None)`

Nuair a úsáideann tú aicearraí rindreála Django, úsáidtear ranganna CSS chun réimsí nó réimsí foirme riachtanacha ina bhfuil earráidí a léiriú. Má tá foirm á rindreáil agat de láimh, is féidir leat rochtain a fháil ar na ranganna CSS seo ag baint úsáide as an modh css\_classes:

```pycon
>>> f = ContactForm(data={"message": ""})
>>> f["message"].css_classes()
'required'
```

Más mian leat roinnt ranganna breise a sholáthar i dteannta leis an earráid agus na ranganna riachtanacha a d'fhéadfadh a bheith ag teastáil, is féidir leat na ranganna sin a sholáthar mar argóint:

```pycon
>>> f = ContactForm(data={"message": ""})
>>> f["message"].css_classes("foo bar")
'foo bar required'
```

#### `BoundField.get_context()`

Tabhair ar ais an gcomhthéacs teimpléid chun an réimse a rin Is é an comhthéacs atá ar fáil ná “réimse” mar shampla an réimse ceangailte.

#### `BoundField.label_tag(contents=None, attrs=None, label_suffix=None, tag=None)`

Déanann sé clib lipéad don réimse foirme ag baint úsáide as an teimpléad a shonraítear ar:attr: .form.template\_name\_label.

Is é an comhthéacs atá ar fáil:

- `field`: An cás seo den :class: Boundfield.
- `contents`: De réir réamhshocraithe teaghrán comhcheangailte de:attr: BoundField.label agus:attr: Form.label\_suffix (nó:attr: Field.label\_suffix, má tá sé socraithe). Is féidir leis na hargóintí `contents` agus `label_suffix` a shárú é seo.
- `attrs`: `dict` ina bhfuil `for`,: attr: Form.requred\_CSS\_Class, agus `id`. Gintear ```id ``ag giuirléid an réimse ``attrs``` nó:attr: BoundField.auto\_id. Is féidir tréithe breise a sholáthar leis an argóint `attrs`.
- `use_tag`: Boolean atá `True` má tá id\` ag an lipéad. Má tá `False` fágann an teimpléad réamhshocraithe an tag .
- `tag`: Sreang roghnach chun an chlib a shaincheapadh, réamhshocraithe go `lipéad`.

> **Tip**
>
> I do theimpléad is é `field` an sampla den `Boundfield`. Dá bhrí sin field.field\` accesses:attr: BoundField.field an réimse a dhearbhíonn tú, m.sh. `Forms.charfield`.

Chun clib lipéad réimse foirme a léiriú ar leithligh, is féidir leat a mhodh label\_tag () a ghlaoch:

```pycon
>>> f = ContactForm(data={"message": ""})
>>> print(f["message"].label_tag())
<label for="id_message">Message:</label>
```

Más mian leat an rindreáil a shaincheapadh is féidir é seo a bhaint amach tríd an tréith: attr: .form.template\_name\_label a shárú nó níos ginearálta tríd an teimpléad réamhshocraithe a shárú, féach freis:ref: overriding-built-in-form-templates.

#### `BoundField.legend_tag(contents=None, attrs=None, label_suffix=None)`

\<legend\>Glaonna: Meth: .label\_tag le `tag = 'legend'` chun clibeanna ```` `a rinneadh an lipéad. <label>Tá sé seo úsáideach agus giuirléidí raidió agus bosca seiceála iolracha á rindreáil ina bhféad <legend>fadh ```a bheith níos oiriúnaí ná` ```` .

#### `BoundField.render(template_name=None, context=None, renderer=None)`

Tugtar as\_field\_group ar an modh rindreála. Tá gach argóint roghnach agus réamhshocraithe:

- `ainm_teimpléad`: :attr: .BoundField.Template\_Ainm
- `context`: Luach ar ais ag: meth: .boundfield.get\_context
- `renderer`: Luach ar ais ar:attr: .form.default\_renderer

Trí `template_name` a rith is féidir leat an teimpléad a úsáidtear le haghaidh glao amháin a shaincheapadh.

#### `BoundField.value()`

Úsáid an modh seo chun amluach an réimse seo a léiriú mar a dhéanfadh “Giuirléid” é:

```pycon
>>> initial = {"subject": "welcome"}
>>> unbound_form = ContactForm(initial=initial)
>>> bound_form = ContactForm(data={"subject": "hi"}, initial=initial)
>>> print(unbound_form["subject"].value())
welcome
>>> print(bound_form["subject"].value())
hi
```

## Saincheapadh `Boundfield`

#### `Form.bound_field_class`

> **New in Django 5.2**

Define a custom [`BoundField`](#django.forms.BoundField) class to use when rendering
the form. This takes precedence over the project-level
[`BaseRenderer.bound_field_class`](/ga/6.0/ref/forms/renderers/#django.forms.renderers.BaseRenderer.bound_field_class) (along with a custom
[`FORM_RENDERER`](/ga/6.0/ref/settings/#std-setting-FORM_RENDERER)), but can be overridden by the field-level
[`Field.bound_field_class`](/ga/6.0/ref/forms/fields/#django.forms.Field.bound_field_class).

If not defined as a class variable, `bound_field_class` can be set via the
`bound_field_class` argument in the [`Form`](#django.forms.Form) or [`Field`](/ga/6.0/ref/forms/fields/#django.forms.Field)
constructor.

For compatibility reasons, a custom form field can still override
[`Field.get_bound_field()`](/ga/6.0/ref/forms/fields/#django.forms.Field.get_bound_field) to use a custom class, though any of the
previous options are preferred.

You may want to use a custom [`BoundField`](#django.forms.BoundField) if you need to access some
additional information about a form field in a template and using a subclass of
[`Field`](/ga/6.0/ref/forms/fields/#django.forms.Field) isn't sufficient.

For example, if you have a `GPSCoordinatesField`, and want to be able to
access additional information about the coordinates in a template, this could
be implemented as follows:

```
class GPSCoordinatesBoundField(BoundField):
    @property
    def country(self):
        """
        Return the country the coordinates lie in or None if it can't be
        determined.
        """
        value = self.value()
        if value:
            return get_country_from_coordinates(value)
        else:
            return None

class GPSCoordinatesField(Field):
    bound_field_class = GPSCoordinatesBoundField
```

Anois is féidir leat rochtain a fháil ar an tír i dteimpléad le `{{form.coordinates.country}}`.

You may also want to customize the default form field template rendering. For
example, you can override [`BoundField.label_tag()`](#django.forms.BoundField.label_tag) to add a custom class:

```
class StyledLabelBoundField(BoundField):
    def label_tag(self, contents=None, attrs=None, label_suffix=None, tag=None):
        attrs = attrs or {}
        attrs["class"] = "wide"
        return super().label_tag(contents, attrs, label_suffix, tag)

class UserForm(forms.Form):
    bound_field_class = StyledLabelBoundField
    name = CharField()
```

This would update the default form rendering:

```pycon
>>> f = UserForm()
>>> print(f["name"].label_tag)
<label for="id_name" class="wide">Name:</label>
```

To add a CSS class to the wrapping HTML element of all fields, a `BoundField`
can be overridden to return a different collection of CSS classes:

```
class WrappedBoundField(BoundField):
    def css_classes(self, extra_classes=None):
        parent_css_classes = super().css_classes(extra_classes)
        return f"field-class {parent_css_classes}".strip()

class UserForm(forms.Form):
    bound_field_class = WrappedBoundField
    name = CharField()
```

This would update the form rendering as follows:

```pycon
>>> f = UserForm()
>>> print(f)
<div class="field-class"><label for="id_name">Name:</label><input type="text" name="name" required id="id_name"></div>
```

Alternatively, to override the `BoundField` class at the project level,
[`BaseRenderer.bound_field_class`](/ga/6.0/ref/forms/renderers/#django.forms.renderers.BaseRenderer.bound_field_class) can be defined on a custom
[`FORM_RENDERER`](/ga/6.0/ref/settings/#std-setting-FORM_RENDERER):

*`mysite/renderers.py`*

```python
from django.forms.renderers import DjangoTemplates

from .forms import CustomBoundField

class CustomRenderer(DjangoTemplates):
    bound_field_class = CustomBoundField
```

*`settings.py`*

```python
FORM_RENDERER = "mysite.renderers.CustomRenderer"
```

## Comhaid uaslódaithe a cheangal le foirm

Tá sé beagán níos casta déileáil le foirmeacha a bhfuil réimsí `Filefield` agus `Imagefield` ná gnáthfhoirm.

Ar dtús, d'fhonn comhaid a uaslódáil, beidh ort a chinntiú go sainmhíníonn d'eilimint \`\` an enctype\` i gceart mar \<form\>\`\`\`"multipart/form-sona":

```html
<form enctype="multipart/form-data" method="post" action="/foo/">
```

Ar an dara dul síos, nuair a úsáideann tú an fhoirm, ní mór duit na sonraí comhad a cheangal. Láimhseálfar sonraí comhaid ar leithligh le gnáthshonraí foirme, mar sin nuair a bhíonn FileField\` agus `ImageField` i d'fhoirm, beidh ort an dara argóint a shonrú nuair a cheanglaíonn tú d'fhoirm. Mar sin má leathnaímid ár bhFoirm Teagmhála chun `ImageField` ar a dtugtar mugshot a áireamh, ní mór dúinn na sonraí comhaid ina bhfuil an íomhá mugshot a cheangal:

```pycon
# Bound form with an image field
>>> from django.core.files.uploadedfile import SimpleUploadedFile
>>> data = {
...     "subject": "hello",
...     "message": "Hi there",
...     "contact_email": "foo@example.com",
...     "urgent": True,
... }
>>> file_data = {"mugshot": SimpleUploadedFile("face.jpg", b"file data")}
>>> f = ContactFormWithMugshot(data, file_data)
```

Go praiticiúil, de ghnáth sonróidh tú `Request.Files` mar fhoinse sonraí comhad (díreach mar a úsáideann tú `Request.post` mar fhoinse sonraí foirme):

```pycon
# Bound form with an image field, data from the request
>>> f = ContactFormWithMugshot(request.POST, request.FILES)
```

Tá foirm neamhcheangailte a thógáil mar an gcéanna agus i gcónaí - fág an dá shonraí foirme\* agus\* sonraí comhaid:

```pycon
# Unbound form with an image field
>>> f = ContactFormWithMugshot()
```

### Tástáil le haghaidh foirmeacha ilpháirteach

#### `Form.is_multipart()`

Má tá tuairimí nó teimpléid in-athúsáidte á scríobh agat, b'fhéidir nach bhfuil a fhios agat roimh am an bhfoirm ilpháirteach í d'fhoirm nó nach bhfuil. Insíonn an modh is\_multipart () duit an bhfuil ionchódú ilpháirteach ag teastáil ón bhfoirm le haghaidh aighneachta:

```pycon
>>> f = ContactFormWithMugshot()
>>> f.is_multipart()
True
```

Seo sampla den chaoi a bhféadfá é seo a úsáid i dteimpléad:

```html+django
{% if form.is_multipart %}
    <form enctype="multipart/form-data" method="post" action="/foo/">
{% else %}
    <form method="post" action="/foo/">
{% endif %}
{{ form }}
</form>
```

## Foirmeacha fo-aicmithe

Má tá iliomad ranganna `Foirme` agat a roinneann réimsí, is féidir leat fo-aicmiú a úsáid chun iomarcaíocht a bhaint.

Nuair a dhéanann tú rang saincheaptha Foirm a fho-aicmiú, beidh gach réimse den tuismitheoir aicme (anna) san fho-aicme mar thoradh air, agus na réimsí a shainmhíníonn tú sa fho-aicme ina dhiaidh sin.

In this example, `ContactFormWithDepartment` contains all the fields from
`ContactForm`, plus an additional field, `department`. The `ContactForm`
fields are ordered first:

```pycon
>>> class ContactFormWithDepartment(ContactForm):
...     department = forms.CharField()
...
>>> f = ContactFormWithDepartment(auto_id=False)
>>> print(f)
<div>Subject:<input type="text" name="subject" maxlength="100" required></div>
<div>Message:<textarea name="message" cols="40" rows="10" required></textarea></div>
<div>Contact email:<input type="email" name="contact_email" required></div>
<div>Urgent:<input type="checkbox" name="urgent"></div>
<div>Department:<input type="text" name="department" required></div>
```

Is féidir foirmeacha iolracha a fho-aicmiú, ag caitheamh le foirmeacha mar mheascáin. Sa sampla seo, tá fo-aicmí `Beatleform` agus `InstrumentForm` araon (san ord sin), agus cuimsíonn a liosta réimsí na réimsí ó na tuismitheoireachtaí:

```pycon
>>> from django import forms
>>> class PersonForm(forms.Form):
...     first_name = forms.CharField()
...     last_name = forms.CharField()
...
>>> class InstrumentForm(forms.Form):
...     instrument = forms.CharField()
...
>>> class BeatleForm(InstrumentForm, PersonForm):
...     haircut_type = forms.CharField()
...
>>> b = BeatleForm(auto_id=False)
>>> print(b)
<div>First name:<input type="text" name="first_name" required></div>
<div>Last name:<input type="text" name="last_name" required></div>
<div>Instrument:<input type="text" name="instrument" required></div>
<div>Haircut type:<input type="text" name="haircut_type" required></div>
```

Is féidir `Field` a bhaint go dearbhaithe ó rang tuismitheoirí trí ainm an réimse a shocrú go None ar an bhfo-aicme. Mar shampla:

```pycon
>>> from django import forms

>>> class ParentForm(forms.Form):
...     name = forms.CharField()
...     age = forms.IntegerField()
...

>>> class ChildForm(ParentForm):
...     name = None
...

>>> list(ChildForm().fields)
['age']
```

## Réamhréamhacha le haghaidh foirmeacha

#### `Form.prefix`

Is féidir leat roinnt foirmeacha Django a chur taobh istigh de chlib `<form>` amháin. Chun a spás ainmneacha féin a thabhairt do gach `Form`, bain úsáid as an argóint eochairfhocal prefix\`:

```pycon
>>> mother = PersonForm(prefix="mother")
>>> father = PersonForm(prefix="father")
>>> print(mother)
<div><label for="id_mother-first_name">First name:</label><input type="text" name="mother-first_name" required id="id_mother-first_name"></div>
<div><label for="id_mother-last_name">Last name:</label><input type="text" name="mother-last_name" required id="id_mother-last_name"></div>
>>> print(father)
<div><label for="id_father-first_name">First name:</label><input type="text" name="father-first_name" required id="id_father-first_name"></div>
<div><label for="id_father-last_name">Last name:</label><input type="text" name="father-last_name" required id="id_father-last_name"></div>
```

Is féidir an réimír a shonrú freisin ar an rang foirme:

```pycon
>>> class PersonForm(forms.Form):
...     ...
...     prefix = "person"
...
```
