Django: Display form name in template with prefix

家住魔仙堡 提交于 2019-12-22 05:13:11

问题


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?

Example:

Let's say I create a form in views.py and include a prefix like this:

myform = SomeForm(prefix="prefix")

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 }}">

will generate:

<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?


回答1:


You can use html_name instead:

<input name="{{ myform.username.html_name }}">

That should add the prefix as needed



来源:https://stackoverflow.com/questions/18123695/django-display-form-name-in-template-with-prefix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!