I'm trying to create a logic in Django to check if all the TabularInline
items are saved before saving the model itself. here is the code am using:
def save_formset(self, request, form, formset, change):
instances = formset.save(commit=False)
for instance in instances:
item_count_in_origin = instance.prc_item.quantity
print(item_count_in_origin)
if instance.quantity > item_count_in_origin:
messages.error(request, 'Quantity is higher than origin branch.')
return
else:
for item in instances:
if item.id is not None:
item.close()
else:
formset.save()
def save_model(self, request, obj, form, change):
if obj.transfer_items.all().count() != 0:
user = request.user
if self.save_formset:
if not change:
obj.solicitor = user
obj.date_solicited = datetime.now()
created_status = Status.objects.get(name=StatusEnum.CREATED)
obj.status = created_status
return super(TransferenceAdmin, self).save_model(request, obj, form, change)
else:
messages.error(request, 'Quantity is higher than origin branch.')
return
when the condition if instance.quantity > item_count_in_origin:
it works right and bring back an error, but when it is false and we go the part of
for item in instances:
if item.id is not None:
item.close()
else:
formset.save()
it fails with the error save() prohibited to prevent data loss due to unsaved related object 'xxxxxxxx'.
UPDATE
I've changed if item.id is not None:
to if item.id is None:
to make sure that item.close()
run only on open but not saved instances.
And the error became 'TransferRequestItem' object has no attribute 'close'
I think this is the wrong way to close an open instance.