Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save the same form more than once in Django 1.8?

Tags:

python

django

I have a model Product and a corresponding form Product and I need to update the stock with lets say 5 product, so I input the data for the Product and ask how many items of this product I want to store, because all products to save are the same, except for Django default ID, i was thinking of doing something like this in the view:

for i in range(0, 5):
   form.save()

Unfortunately this only saves the last form.

How else can I achieve what I need?

like image 575
Crixx93 Avatar asked Oct 08 '15 22:10

Crixx93


1 Answers

Calling save with commit=False returns an instance that is not saved to the database.

instance = form.save(commit=False)

You can the save the instance multiple times in a loop. By setting the primary key to None, a new object will be saved each time.

for i in range(0, 5):
    instance.pk = None
    instance.save()
like image 124
Alasdair Avatar answered Nov 06 '22 19:11

Alasdair