Шаблон Django неправильно удаляет запись

Это код моего шаблона

<tbody>
    {% for item in items %}
    <tr class="text-black">
      <td>{{ item.name }}</td>
      <td>{{ item.description }}</td>
      <td>
        <a
          href="{% url 'menu-options-update' item.id %}"
          class="btn btn-sm btn-user edit"
        >
          <!-- <i class="far fa-edit"></i> -->
          <i class="fas fa-pencil-alt"></i
        ></a>
        <a
          data-toggle="modal"
          class="btn btn-sm btn-user delete btn--show-modal"
          href="#myModal"
          data-confirm="Are you sure to delete this item?"
          ><i class="fas fa-trash"></i
        ></a>
      </td>
      <div class="modal1 hidden">
        <button class="btn--close-modal">&times;</button>
        <h2 class="modal__header">Do you want to delete this record?</h2>
        <div class="deletModalBtnContainer">
          <a
            href="{% url 'menu-options-delete' item.id %}"
            class="delete-final btn"
            >Delete</a
          >
          <a href="#" class="cencel-modal btn btn-cancels-close-modal"
            >Cencel</a
          >
        </div>
      </div>
    </tr>
    {% endfor %}
  </tbody>

И это мое мнение

  item = MenuOptions.objects.get(id=id)
  item.delete()

Этот код всегда выбирает первый id в данных таблицы, а не тот, на котором я щелкнул. Допустим, в моей таблице 5 строк, и я хочу удалить 4-ю строку, но после нажатия на кнопку delete удаляется 1-я строка.

У меня такая же проблема, после 20-часового исследования я получил следующее решение:

вам нужно отправить id в modal, используя data-target="#{{ item.id }}" и установить id modal: id="{{ item.id }}">, чтобы modal мог передать этот id в view.py

<tbody>
{% for item in items %}
<tr class="text-black">
    <td>{{ item.name }}</td>
    <td>{{ item.description }}</td>
    <td>
        <a href="{% url 'menu-options-update' item.id %}" class="btn btn-sm btn-user edit">
            <!-- <i class="far fa-edit"></i> -->
            <i class="fas fa-pencil-alt"></i>
        </a>
        <a data-toggle="modal" data-target="#{{ item.id }}" class="btn btn-sm btn-user delete btn--show-modal"
            href="#myModal" data-confirm="Are you sure to delete this item?"><i class="fas fa-trash"></i></a>
        <div class="modal1 hidden" id="{{ item.id }}">
            <button class="btn--close-modal">&times;</button>
            <h2 class="modal__header">Do you want to delete this record?</h2>
            <div class="deletModalBtnContainer">
                <a href="{% url 'menu-options-delete' item.id %}" class="delete-final btn">Delete</a>
                <a href="#" class="cencel-modal btn btn-cancels-close-modal">Cencel</a>
            </div>
        </div>
    </td>

</tr>
{% endfor %}
Вернуться на верх