Home > Software design >  Save two instances on same model in django
Save two instances on same model in django

Time:11-18

In my case, it a treasury managing app, the task is i want to transfer an amount x from treasury A to treasury B, from bank to cashier or from paypal acc to my bank, i m adding two instances to same table (treasuryitem) but with different details (treasury). in the code bellow, i got two instances but the field treasury doesn t save as i choose, it save same, for ex treasury A in both instances. Also, i would like to fill only first form and treasury of second form, and the other fields of second form have to save automatically (name=name, date=date, debit=credit, credit=debit). Anyone can help pls. thanks in advance

MODEL :

class Treasury(models.Model):
    name = models.CharField(max_length=256)

class TreasuryItem(models.Model):
    treasury = models.ForeignKey('Treasury', on_delete=models.CASCADE)
    date = models.DateField(default=timezone.now)
    name = models.CharField(max_length=256)
    debit = models.DecimalField(max_digits=20, decimal_places=2, null=True, blank=True)
    credit = models.DecimalField(max_digits=20, decimal_places=2, null=True, blank=True)

FORM :

class TreasuryItem1Form(ModelForm):

    class Meta:
        model = TreasuryItem
        fields = "__all__"


class TreasuryItem2Form(ModelForm):

    class Meta:
        model = TreasuryItem
        fields = "__all__"

VIEW:

def TreasuryItem_Create(request, pk):
    treasurys = Treasury.objects.all()
    treasury = treasurys.get(id=pk)
    form1 = TreasuryItem1Form()
    form2 = TreasuryItem2Form()
    if request.method == 'POST':
        form1 = TreasuryItem1Form(request.POST)
        form2 = TreasuryItem2Form(request.POST)
        if form1.is_valid() and form2.is_valid():
            form1.save()
            form2.save()
            return redirect('treasury_profile', pk)

CodePudding user response:

You don't need two form instances. Simply re-save the instance after sets id as None in order to force a new insert in the database.


def TreasuryItem_Create(request, pk):
    treasurys = Treasury.objects.all()
    treasury = treasurys.get(id=pk)
    form1 = TreasuryItem1Form()
    if request.method == 'POST':
        form1 = TreasuryItem1Form(request.POST)
        if form1.is_valid() and form2.is_valid():
            treasury_item = form1.save()
            treasury_item.id = None
            # modify any other field if need
            # treasury_item.name = 'my new name`
            treasury_item.save()
            return redirect('treasury_profile', pk)
  • Related