如何创建接收记录并在django中创建以单一形式接收的项目

How can I create a receiving record and create the item received in a single form in django

我想创建一个收货记录并创建从一个表格收到的项目:

我的模特:

class Item(models.Model):
    item_number = models.CharField(max_length=55)
    item_name = models.CharField(max_length=55)

class Receive(models.Model):
    receive_date = models.DateField()
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    qty = models.PositiveIntegerField()

我的模型:

class RecievingForm(forms.ModelForm):
    class Meta:
        model = Receive
        fields = ('item_number', 'item_name', 'receive_date', 'qty')

我的看法:

if request.method == "POST":
    form = RecievingForm(request.POST)
    if form.is_valid():
        # form.item.save() ... Here I want to create the item
        # form.receive.save() ... Here I want to create the receive record
        return redirect('receiving')
else:
    context = {
        'form': RecievingForm(),
    }
    return render(request, 'production/add_rcv.html', context)

假设每条收货记录只有1条,且假设该条在DB中不存在

经过广泛的研究和反复试验,我相信已经弄明白了。

我的模型:

class ItemForm(forms.ModelForm):
    class Meta:
        model = Item
        fields = ('item_number', 'item_name')

class RecievingForm(forms.ModelForm):
    class Meta:
        model = Receive
        fields = ('receive_date', 'qty')

我的看法:

if request.method == "POST":
    i_form = ItemForm(request.POST)
    r_form = RecievingForm(request.POST)
    if i_form.is_valid() and r_form.is_valid():
        this_item = i_form.save()
        this_receive.item = this_item
        this_receive.save()
        return redirect('receiving')
    context = {
        'i_form': i_form,
        'r_form': r_form,
    }
    return render(request, 'production/add_rcv.html', context)