Python 3.x 无法在django模板中发布所需数据
我想在django中将一个表单从我的html发布到views.py,但我不能这样做 这是我的html。此表单应将下载图像的url发布到views.py函数Python 3.x 无法在django模板中发布所需数据,python-3.x,django,django-views,django-forms,django-templates,Python 3.x,Django,Django Views,Django Forms,Django Templates,我想在django中将一个表单从我的html发布到views.py,但我不能这样做 这是我的html。此表单应将下载图像的url发布到views.py函数 {% for x in photo %} <a class="down" href="{{x.image.url}}" onclick="myfunc()" download="none">get</a>
{% for x in photo %}
<a class="down" href="{{x.image.url}}" onclick="myfunc()" download="none">get</a>
<form action="/image_info/" method="POST" id='dform'>
{% csrf_token %}
<input name='d_button' type="hidden" value="{{x.image.url}}">
</form>
{% endfor %}
这是我的观点。这应该从表单中获取图像url,并将其显示在新页面中
def show_image():
image_url = request.POST.get('d_button', None)
return render(request, 'show_image.html', {'image': image_url)
但我的问题是表单并没有返回被点击图像的url,而是返回第一个链接的url。比如说
link1
link2
link3
link4
如果我点击link3,它会下载link3中的图片,但会发布link1的url
这是一个有点棘手的解释,但这是我能做的最好的
提前感谢。HTML ID应该是唯一的。您在生成这些表单时正在循环,因此会生成一组重复的ID,因此当您编写
document.getElementById(“dform”)
时,会选择第一个匹配的元素
一种解决方案是使用forloop.counter
生成唯一的ID并使用它们。我们将这些ID设置为锚点上的属性,并将锚点元素传递给onclick函数:
{% for x in photo %}
<a class="down" href="{{x.image.url}}" onclick="myfunc(this)" data-target="dform-{{ forloop.counter }}" download="none">get</a>
<form action="/image_info/" method="POST" id='dform-{{ forloop.counter }}'>
{% csrf_token %}
<input name='d_button' type="hidden" value="{{x.image.url}}">
</form>
{% endfor %}
{photo%%中x的%
{%csrf_令牌%}
{%endfor%}
现在在javascript中:
<script type="text/javascript">
function myfunc(elem)
{
document.getElementById(elem.getAttribute("data-target")).submit();
console.log('hello');
}
</script>
函数myfunc(elem)
{
document.getElementById(elem.getAttribute(“数据目标”)).submit();
log('hello');
}
模板中photo的值是多少?@Vincent photo是一个查询集,其中包含作为图像的模型的所有对象
<script type="text/javascript">
function myfunc(elem)
{
document.getElementById(elem.getAttribute("data-target")).submit();
console.log('hello');
}
</script>