def transaction(request): if request.user.is_authenticated(): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = TransactionForm(request.POST) EntryFormSet = formset_factory(EntryForm, extra=10) formset = EntryFormSet(request.POST) # check whether it's valid: if form.is_valid() and formset.is_valid(): # process the data in form.cleaned_data as required in_type = form.cleaned_data['type'] in_party = form.cleaned_data['party'] in_description = form.cleaned_data['description'] # create the transaction # todo be careful because there is a DB hit with create, consider using save transaction = Transaction.objects.create(transaction_type=in_type, transaction_actor=request.user.username, transaction_party=in_party, transaction_description=in_description) # now save the data for each entry in the formset new_entries = [] for entry_form in formset: in_transaction_gkey = transaction in_product = entry_form.cleaned_data.get('product') in_color = entry_form.cleaned_data.get('color') in_quantity = entry_form.cleaned_data.get('quantity') if in_transaction_gkey and in_product and in_color and in_quantity: # Adjust the stock try: product = Product.objects.get(product_name=in_product, product_color=in_color) except Product.DoesNotExist: product = Product(product_name=in_product, product_color=in_color) product.save() try: stk = Stock.objects.get(product_gkey=product) except Stock.DoesNotExist: stk = Stock(product_gkey=product) stk.save() if transaction.transaction_type == 'In': stk.quantity = stk.quantity + in_quantity else: stk.quantity = stk.quantity - in_quantity stk.save() new_entries.append(Entry(transaction_gkey=in_transaction_gkey, product_gkey=product, quantity=in_quantity)) #todo: add try catch #todo: add verification no 2 same product Entry.objects.bulk_create(new_entries) # redirect to a new URL: return render(request,'mafia/index.html') # if a GET (or any other method) we'll create a blank form else: form = TransactionForm() EntryFormSet = formset_factory(EntryForm,extra=10) formset = EntryFormSet() return render(request, 'mafia/transaction.html', {'form': form, 'formset': formset}) else: return render(request, 'mafia/request_login.html')