Daniel Wedlund
Daniel Wedlund

Reputation: 814

Create multiple instances of object from one form in django

I have a case where I want a very simple "webshop". A sale consists of one or many items.

class Sale(models.Model):
  timestamp = models.DateTimeField()
  value = models.FloatField()


class Item(models.Model):
  seller = models.ForeignKey(Seller)

  value = models.FloatField()
  timestamp = models.DateTimeField()

  sale = models.ForeignKey(Sale)

What I am struggling with is to create a form that creates a Sale that in turn contains multiple Items. I have conceptually a simple page setup that has a basic "shopping cart" where the user can add multiple items.

But I dont know how to get the data in a good format back to the django app to interpret, validate, create the instances etc.

I am starting to think about a solution where I jus send back a JSON-snippet containing the cart via Javascript and let django app interpret that bit of information... but I would rather be able to use the django forms.

Any guidelines, ideas, solutions?

Upvotes: 3

Views: 3699

Answers (1)

CORTIZ
CORTIZ

Reputation: 101

Ran into your problem just now. Maybe you have found a solution since it's been 5 years already. But if not, you can use formset factory for the model Item and the usual model form for the model Sale. This helps you create multiple instances of Item by rendering n number times your Item model in a form.

You can check this link https://medium.com/all-about-django/adding-forms-dynamically-to-a-django-formset-375f1090c2b0. It provides good example of how to use formset factory.

Upvotes: 3

Related Questions