使用基于函数的视图获取 pk_id

Get pk_id using function based view

我在获取模板中的 pk 时遇到问题。当我 select 一条记录时,它总是 returns 最后一个 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">&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 中,我只想首先打印 item/record 的 pk ID,我在 table 中使用模态 select .但是,它总是在我的数据库中获取最后一条记录。

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

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