How to automatically refresh azure access token using Django

I have a django web app that connects to a mssql database on azure using a user assigned managed identity. The app use DefaultAzureCredential from azure.identity to get a azure token for the managed identity. However, after a while the token expires, the app cannot connect to the database anymore. How to automatically refresh the azure access token properly?
In settings.py,

def get_token():
    credential = DefaultAzureCredential(managed_identity_client_id = 'my-managed-identity-client-id')
    token = credential.get_token("https://database.windows.net/.default")
    return token.token
DATABASES = {
    'default': {
        'ENGINE': 'mssql',
        'NAME': 'my-db-name',
        'HOST': 'server-name',
        'PORT': '1433',
        "TOKEN": get_token(),
        'OPTIONS': {
            'driver': 'ODBC Driver 17 for SQL Server',
        },
    }
}

I tried some middleware approaches, but all failed to refresh the token eventually.

I have the same scenario just that i’m trying to connect to Postgres db. Any ideas on this?