Trying to insert transactions fails

Hi,

I am trying to insert many records from a database into dgraph.
However, the process fails with the following message:

response = txn.mutate(set_obj=json_payload)

File “/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pydgraph/txn.py”, line 76, in mutate
return self.do_request(req, timeout=timeout, metadata=metadata, credentials=credentials)
File “/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pydgraph/txn.py”, line 91, in do_request
raise errors.TransactionError(‘Transaction has already been committed or discarded’)
pydgraph.errors.TransactionError: Transaction has already been committed or discarded

Here is the function to insert the data:
def create_data(client):
# Create a new transaction.
txn = client.txn()
TXN = DbQuery()

# Create data.
for item in db:
        try:
            json_payload = {
                # 'uid': '_:did',
                'Transaction.seqNo': item['seqNo'],
                'Transaction.type': resolve_txn_type(item),
                'Transaction.time': resolve_txn_time(item),
                'Transaction.endorser': None,
                'Transaction.author': None,
                'DID.did': did,
                'DID.verkey': verkey,
                'DID.role': role,
                'DID.alias': alias,
            }

            print('JSON UPDATE IS',json_payload)

            # Run mutation.
            response = txn.mutate(set_obj=json_payload)
            # Commit transaction.
            txn.commit()

            # print('Created Transaction with uid = {}'.format(response.uids['did']))
            print('Created Transaction with seqNo = {} and DID {}'.format(item['seqNo'], did))
        # except TxnConflictException as ex:
        except Exception as e:
            print("TX ERROR", e.__class__, "occurred.")
        finally:
            # Clean up. Calling this after txn.commit() is a no-op and hence safe.
            # print('discarding tx')
            txn.discard()

Any ideas or pointers will be appreciated?

Welcome @eax
The opening of a new transaction, txn = client.txn() needs to be inside the for loop.