Невозможно отправить несколько сообщений в базу данных в Django

Моя цель - отправить все добавленные элементы в мою базу данных. При отправке данных в базу данных ошибки нет, но моя форма заполняет базу данных только одной записью, т.е. "Значение последнего ввода среди всех вводов". Я новичок в разработке Django, пожалуйста, подскажите, где я делаю неправильно.

Мой Html выглядит следующим образом: enter image description here

Таблицы в моей базе данных:

Первичный ключ Таблица: enter image description here

Таблица иностранных ключей: enter image description here

  1. Table that already contains items.
  2. Table that is made to receive the items from table one. I am just trying to learn how to post data of multiple inputs, otherwise there isn't any logic behind this operation.

Из models.py:

class Item(models.Model):
    Id = models.AutoField(primary_key=True)
    itemName  = models.CharField(max_length=30,unique=True)
    cId = models.ForeignKey(Category,on_delete=CASCADE)
    def __str__(self):
        return self.itemName

class TransferedItems(models.Model):
    Id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    item = models.ForeignKey(Item, on_delete=CASCADE)

Из файла views.py:

def transfer(request):
    if request.method == "POST":
        a = request.POST.get("a");
        obj = TransferedItems(item_id = a);
        obj.save();
        return HttpResponse("sent")
    else:
        return HttpResponse("form submission failed")

Из HTML:

<html lang="en">
<body>

    <div class="maindiv">
        <div class="divA">
            <label for="coffee">Coffee</label>
            <select name="coffee" id="coffee">
                {% for opt in opts %}
                <option value="{{opt.Id}}"> {{opt.itemName}} </option>
                {% endfor %}
            </select>
            <button onclick="addtocart()">ADD</button>
        </div>
        <div class="divB">
            <form method="post" id="cart-screen-form" action="transfer">
                {% csrf_token %}
                <label>ADDED ITEMS:</label>

              <!--Every click to addtocart() results in the creation 
               of a new div that contains a label and an input -->
               <!--Please see Javascript code-->

                <button type="submit">SEND TO DB</button>
            </form>

        </div>
    </div>

</body>

</html>

От JS:

function addtocart() {
    let selectbox_os = document.getElementById("coffee");

    let csform = document.getElementById("cart-screen-form");
    let container = document.createElement("div");
    let item = document.createElement("input");
    let item_label = document.createElement("label");
    container.className = "container";

    item_label.className = "csf-labels";
    item_label.innerText = selectbox_os.options[selectbox_os.selectedIndex].text;
    item.type = "text";
    item.className = "csf-items";
    item.value = selectbox_os.options[selectbox_os.selectedIndex].value;
    item_label.setAttribute("for","a")
    item.setAttribute("name", "a");
    csform.appendChild(container);
    container.append(item_label,item);

}

Основная причина сохранения только одного ввода данных заключается в том, что в js-файле вы создали элемент input и задали его атрибутам имя "a". Таким образом, все поля ввода, создаваемые js, получили имя "a". Поэтому, когда вы отправляете данные формы, запрос в вашем представлении сможет принять только один вход "a", так как в представлении есть один запрос.

Вернуться на верх