Django:在模板中显示带有前缀的表单名称
一段时间以来,我一直在寻找答案,但没有成功。
我基本上想获得包含前缀的表单字段的名称。有人知道怎么做吗?
I have looked around for an answer for this for a while now with no success. I basically want to get the name of a form field with the prefix included. Does anyone know how to do this?
示例:
假设我在views.py中创建了一个表单并包含这样的前缀:
Let's say I create a form in views.py and include a prefix like this:
myform = SomeForm(prefix="prefix")
,然后将其传递给我的模板。如果然后我直接通过{{myform.username}}访问模板中的表单字段,则会得到以下信息(注意,已包含前缀):
and then pass it to my template. If I then access a form field within the template directly I by {{ myform.username }} get something like this (notice that the prefix was included):
<select id="id_prefix-username" name="prefix-username"> ...
但是如果我想手动创建表单标签并仅插入名称,则我没有前缀:
If I however would like to manually create the form tag and just insert the name, then I don't get the prefix with it:
<input name="{{ myform.username.name }}">
会生成:
<input name="username">
注意它现在缺少前缀了。现在,我可以这样做来达到相同的结果:
Notice how it is now missing the prefix. Now, I can do it like this to achieve the same result:
<input name="{{ myform.prefix }}-{{ myform.username.name }}">
但是必须有一种内置的方法吗?
But there must be a built in way to do this?
您可以改用html_name:
You can use html_name instead:
<input name="{{ myform.username.html_name }}">
应该根据需要添加前缀