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

Viewed 20

I would like to create a receiving record and create the item received both from a single form:

My Models:

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()

My ModelForm:

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

My View:

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)

Assuming that every receiving record have only 1 item and assuming that the item does not exist in the DB.

1 Answers

After some extensive research and trial & error, I believe figured it out.

My ModelForm:

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')

My View:

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)
Related