Django: Display form name in template with prefix

2019-05-07 10:10发布

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条回答
我只想做你的唯一
2楼-- · 2019-05-07 10:45

You can use html_name instead:

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

That should add the prefix as needed

查看更多
登录 后发表回答