简体   繁体   English

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

[英]How to get form fields' id in Django

Is there any way to get the id of a field in a template?有什么方法可以获取模板中字段的 id 吗?

In the HTML I get: <input name="field_name" id="id_field_name"...在我得到的 HTML 中: <input name="field_name" id="id_field_name"...

I know I can get the name with {{ field.html_name }} , but is there anything similar for getting the id?我知道我可以使用{{ field.html_name }}获取名称,但是获取 id 有什么类似的吗?
Or can I only get it like this: id_{{ field.html_name }} ?或者我只能这样得到它: id_{{ field.html_name }}

你可以得到这样的ID:

{{ field.auto_id }}

你也可以使用id_for_label

{{ field.id_for_label }}

This doesn't work for every form field. 这不适用于每个表单字段。

For instance {{ form.address.auto_id }} works while {{ form.address.auto_name }} will not. 例如{{ form.address.auto_id }}有效,而{{ form.address.auto_name }}则不然。

However you can use {{ form.address.html_name }} to get the equivalent answer. 但是,您可以使用{{ form.address.html_name }}来获得等效答案。

Here are the docs 这是文档

In Django 2 you can retrieve the ID for a specific field using {{ field.id_for_label }} 在Django 2中,您可以使用{{ field.id_for_label }}检索特定字段的ID

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.每个表单字段都有一个设置为id_<field-name>的 ID 属性,该属性由随附的标签标记引用。 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.您还可以自定义生成标签和 ID 的方式。

So I would like to say id_field-name , you collect the field name from the model.所以我想说id_field-name ,你从模型中收集字段名称。

Here is the link to the documentation这是文档的链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM