Django: Display form name in template with prefix
Asked Answered
L

1

8

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?

Lubalubba answered 8/8, 2013 at 10:28 Comment(3)
{{ myform.prefix }}-{{ myform.username.name }} looks ok to me.Pyretotherapy
Create a custom template tag for it.Sexed
No. There's not a built in way to do this. You'll have to write a custom tag as @Sexed said, or just add the prefix manually like you've done.Aesthetic
A
17

You can use html_name instead:

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

That should add the prefix as needed

Amah answered 31/1, 2014 at 12:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.