Home > Enterprise >  Create Single Forms by Two Models in Django with Dynamic Fields
Create Single Forms by Two Models in Django with Dynamic Fields

Time:02-20

I want to create Django Forms to save transactions for the store. I want a final template similar to this. The ER Diagram for my database is also shown in the image.

HTML tempalte and ER Diagram

My Django Models are:

class Party(models.Model):
    party_id = models.BigAutoField(primary_key=True)
    party_name = models.CharField(max_length=128)
    party_phone = models.CharField(max_length=128)
    party_address = models.CharField(max_length=128)

    def __str__(self):
        return self.party_name

class Items(models.Model):
    item_no = models.BigAutoField(primary_key=True)
    item_type = models.BooleanField(default=True)    
    item_name = models.CharField(max_length=128) 
    item_qty = models.PositiveIntegerField(default=0)
    item_cost = models.PositiveIntegerField(default=0)
    
    def __str__(self):
        return self.item_name

class Sales(models.Model):
    invoice_no = models.BigAutoField(primary_key=True)
    invoice_date = models.DateField(default=date.today)
    party = models.ForeignKey(Party, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.invoice_no)

class SalesTransaction(models.Model):
    sales = models.ForeignKey(Sales, on_delete=models.CASCADE)
    items = models.ForeignKey(Items, on_delete=models.CASCADE)
    purchase_qty = models.PositiveIntegerField(default=0)
    total_cost = models.PositiveIntegerField(default=0)

    def __str__(self):
        return self.item_name

I can achieve this with AJAX but I don't think it is the best solution because lots of validations have to be made with hardcoding.

How can I create Django Form to save data in that multiple tables in a single Save Click?

CodePudding user response:

I have been looking for a way to do the same thing recently. The solution I stumbled upon was to use two form objects under a single <form> tag. You can differentiate between the form objects by giving them prefix attributes before passing to context. For example:

def get_view(request):
    ....
    form1 = Form1(prefix="form1")
    form2 = Form2(prefix="form2")
    return render(request, 'template.html', {'form1': form1, 'form2': form2})

In your template, you would call them as usual under a single form tag:

<form>
    {{ form1.as_p }}
    {{ form2.as_p }}
    <input type='submit'>
</form>

Now in your post view, you can use the prefix to get data of each form individually:

def post_view(request):
    form1 = Form1(request.POST, prefix="form1")
    form2 = Form2(request.POST, prefix="form2")
    ....
  • Related