如何在 Django 中获取表单字段的 id

有没有办法在模板中获取字段的 id?

在 HTML 中我得到: <input name="field_name" id="id_field_name"...

我知道我可以用 {{ field.html_name }}得到这个名字,但是有没有类似的方法可以得到这个 ID 呢?
或者我只能得到这样的: id_{{ field.html_name }}

65060 次浏览

You can get the ID like this:

\{\{ field.auto_id }}

This doesn't work for every form field.

For instance \{\{ form.address.auto_id }} works while \{\{ form.address.auto_name }} will not.

However you can use \{\{ form.address.html_name }} to get the equivalent answer.

Here are the docs

You can also use id_for_label:

\{\{ field.id_for_label }}

In Django 2 you can retrieve the ID for a specific field using \{\{ field.id_for_label }}

This is documented here.

From the documentation-

each form field has an ID attribute set to id_<field-name> , which is referenced by the accompanying label tag. This is important in ensuring that forms are accessible to assistive technology such as screen reader software. You can also customize the way in which labels and ids are generated.

So I would like to say id_field-name , you collect the field name from the model.

Here is the link to the documentation