首页 > 解决方案 > 使用基于函数的视图获取 pk_id

问题描述

我在获取pk模板时遇到问题。当我选择一条记录时,它总是返回最后一个pkID。顺便说一句,我正在使用功能基础视图。这是我的 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">&times;</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。但是,它总是在我的数据库中获取最后一条记录。

标签: pythondjangopython-3.xpostgresqldjango-2.1

解决方案


这是因为您有一个包含所有行的<form>标签。DataCollection您应该为每个表格设置单独的表格,即:

{% for collectionlist in collection %}
  <form method="POST" action="{% url 'single_collection' %}">
  {% csrf_token %}
    ...
  </form>
{% endfor %}

推荐阅读