Вот как я это делаю:
HTML Код
<form>
<label for="">Invoice No</label>
<input type="text">
<label for="">Invoice Date</label>
<input type="date">
<table border="1" id="items">
<tr>
<th>Item Name</th>
<th>Qty</th>
<th>Rate</th>
</tr>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text" id="rate"></td>
</tr>
</table>
<input type="submit">
</form>
JS Код
function createNewRow(){
var table = document.getElementById("items");
var row = table.insertRow(-1);
for(i=0; i<3; i++){
var cell = row.insertCell(-1);
var el = document.createElement("input");
el.setAttribute("type", "text");
cell.appendChild(el)
}
}
$(document).on('keypress', function(e) {
if(e.which == 13 ){
e.preventDefault();
if(e.target.id == "rate"){
var table = document.getElementById("items");
createNewRow();
$("#rate").removeAttr("id");
let lastRow = table.rows[table.rows.length-1];
let lastCell = lastRow.cells[lastRow.cells.length-1];
$(lastCell.firstElementChild).attr("id","rate");
}
}
});
Models.py
from django.db import models
# Create your models here.
class Purchase(models.Model):
invoice_no = models.CharField(max_length=255, primary_key=True)
invoice_date = models.DateField()
def __str__(self):
return '%s' % (self.invoice_no)
class Items(models.Model):
invoice_no = models.ForeignKey(Purchase, on_delete=models.CASCADE)
item_name = models.CharField(max_length=255)
qty = models.IntegerField(default=0)
rate = models.FloatField(default=0)
def __str__(self):
return '%s' % (self.item_name)
Требование:
Требование
Мне нужен конкретный номер счета-фактуры. Я хочу добавить сведения о покупке нескольких товаров и сохранить их в db при отправке. Я пробовал использовать набор форм, но не знаю, где я ошибся
views.py
from django.shortcuts import render
from .models import Items
from .models import Purchase
from django.forms import modelformset_factory
# Create your views here.
def home(request):
ItemsFormSet = modelformset_factory(Items, fields=('item_name', 'qty', 'rate'))
formset = ItemsFormSet(queryset=Items.objects.none())
if request.method == 'POST':
invoice_no = request.POST.get('invoice_no')
invoice_date = request.POST.get('invoice_date')
purchase = Purchase.objects.create(invoice_no=invoice_no, invoice_date=invoice_date)
purchase.save()
formset = ItemsFormSet(request.POST)
instances = formset.save(commit=False)
for i in range(0, len(instances)):
items = Items.objects.create(item_name=instances[i].item_name, qty=instances[i].qty, rate=instances[i].rate, invoice_no=Purchase.objects.last())
items.save()
items = Items.objects.all()
return render(request, 'index.html', {'items': items, 'formset': formset})
Как мы можем добавить сразу несколько элементов без отправки формы?