python - 使用基于函数的视图获取 pk_id
问题描述
我在获取pk
模板时遇到问题。当我选择一条记录时,它总是返回最后一个pk
ID。顺便说一句,我正在使用功能基础视图。这是我的 collection.html:
<form method="POST" action="{% url 'single_collection' %}">
{% csrf_token %}
<table class="table" id="dataTables-example">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Status</th>
<th>Download</th>
</tr>
</thead>
<tbody>
{% for collectionlist in collection %}
<tr>
<td>{{ collectionlist.id }}</td>
<td>{{ collectionlist.sqa_name }}</td>
<td>{{ collectionlist.status }}</td>
<td class="center"><center><button type="button" class="btn btn-link" data-toggle="modal" data-target="#myModaldl{{ collectionlist.id }}" ><span class="glyphicon glyphicon-download-alt"></span></button></center></td>
</tr>
<div class="modal fade collectClass" id="myModaldl{{ collectionlist.id }}" role="dialog" tabindex="-1">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Single Collect</h3>
</div>
<div class="modal-body form-horizontal">
<div class="form-group">
<label for="inputSQAID" class="col-sm-3 control-label">SQA Name</label>
<div class="col-sm-8">
<input type="hidden" name="pk_id" id="pk_id" value="{{ collectionlist.id }}">
<input type="text" class="form-control" name="singlecollect" value="{{ collectionlist.sqa_name }}" id="inputSQAID">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-warning" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-success" name="single_dl">Download</button>
</div>
</div>
</div>
</div>
{% endfor %}
</tbody>
</table>
</form>
这是我的views.py:
def collection(request):
context = {
'collection': DataCollection.objects.all(),
'title': 'Data Collection',
}
return render(request, 'data_collection/collection.html', context)
def single_collect(request):
if request.method == 'POST':
pkid = request.POST.get('pk_id')
print(pkid)
all_data = DataCollection.objects.all()
return render(request, 'data_collection/collection.html', {'title' : 'Data Collection', 'data': all_data})
在我的views.py 中,我只想首先pk
使用模态打印我在表中选择的项目/记录的ID。但是,它总是在我的数据库中获取最后一条记录。
解决方案
这是因为您有一个包含所有行的<form>
标签。DataCollection
您应该为每个表格设置单独的表格,即:
{% for collectionlist in collection %}
<form method="POST" action="{% url 'single_collection' %}">
{% csrf_token %}
...
</form>
{% endfor %}
推荐阅读
- angular - 带有 Jest 的 Angular - TypeError:无法读取 null 的属性“ngModule”
- python - PySide2 代理模型非可通知属性警告
- priority-web-sdk - 在 Priority REST API 中使用 $select 和 $expand 时出现问题
- python - 为什么我应该使用 --user 标志,这是一个好习惯吗?
- typescript - 如何使用对象条目作为打字稿中嵌套对象的索引?
- java - 桌子放在桌子上的演员 (LIBGDX)
- amazon-web-services - 如何确定 s3 文件夹大小?
- docker - 当我在 Google Cloud 上运行 Flutter build apk 时超出内存限制
- lua - Pandoc Lua 过滤器:如何访问标题变量?
- vue.js - 刷新后Vue-Persist不重新加载状态