Title: Change href to django iterated object with Javascript
Tags: javascript;python;django
Question: I have a template with a formset:
<form method='post' id=&quot;data_form&quot;&gt;
{% csrf_token %}
{{ my_formset.management_form }}
<table&gt;
...
<tbody&gt;
{% for form in my_formset %}
<tr&gt;
{% for field in form %}
{% if 'inventory_number' in field.auto_id %}
<td&gt;
<a href=&quot;{% url 'invent:update_item' pk %}&quot; class=&quot;update-link&quot;&gt;
{{ field.value }}
</a&gt;
</td&gt;
{% else %}
<td&gt;{{ field }}</td&gt;
{% endif %}
{% endfor %}
</tr&gt;
{% endfor %}
</tbody&gt;
</table&gt;
</form&gt;
Since the field &quot;inventory_number&quot; is supposed to be immutable anyway, I want it to link to the UpdateView of this item. I can get pk for this item with JS:
var links = document.getElementsByClassName('update-link')
for (let i = 0; i < links.length; i++){
let link_row = links[i].parentNode.parentNode
let item_id = link_row.lastElementChild.childNodes[1].attributes.value.value
Now how do I pass this item_id form the script to django {% url 'invent:update_item' pk %}? Or maybe there's a better way to do it all together.
UPDATE
Fixed it like this:
{% for field in form %}
{% if '-id' in field.auto_id %}
{% if field.value %}
<td&gt;
<a href=&quot;{% url 'invent:update_item' field.value %}&quot;&gt;
<img src=&quot;{% static 'img/edit.png' %}&quot;&gt;
{{ field }}
</a&gt;
</td&gt;
{% else %}
{{ field }}
{% endif %}
{% else %}
<td&gt; {{ field }}</td&gt;
{% endif %}
{% endfor %}
Not exactly what I wanted, but it will do.


Here is another answer: Did you try field.value instead of pk in {% url %} tag?
{% if 'inventory_number' in field.auto_id %}
<td&gt;
<a href=&quot;{% url 'invent:update_item' field.value %}&quot; class=&quot;update-link&quot;&gt;
{{ field.value }}
</a&gt;
</td&gt;
{% else %}
Comment for this answer: ```field.value``` is not a pk for this object. It's just a string
Comment for this answer: But If I use hidden id input instead as a link, that should actually work,

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2021:00:08/18/21', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<javascript><python><django>', 'Title': 'Change href to django iterated object with Javascript', 'ViewCount': 41, 'id': 68835628, 'user_AboutMe': None, 'user_AccountId': 18071302.0, 'user_DisplayName': 'Viktor', 'user_Reputation': 301.0, 'user_Views': 39.0, 'user_id': 13135901.0}}