I’m trying to run a admin action async but I’m unable to print a message after the function finished using modeladmin.message_user()
.
As a workaround, I currently run the async code inside the function with async_to_sync()
but I would like to run it async if possible.
Using this code, the message does not get printed:
@admin.action(description="Re-Sync selected customers from API")
async def sync_customers(modeladmin, request, queryset):
"""Sync the selected customers from API"""
for customer in queryset:
customer = await api_client.get_customers(customer.id)
await save_customer(customer)
await sync_to_async(modeladmin.message_user)(
request,
ngettext(
'%d customer was successfully synced.',
'%d customers were successfully synced.',
len(queryset),
) % len(queryset), messages.SUCCESS)
However this works:
@admin.action(description="Re-Sync selected customers from API")
def sync_customers(modeladmin, request, queryset):
"""Sync the selected customers from API"""
for customer in queryset:
customer = async_to_sync(api_client.get_customers)(customer.id)
async_to_sync(save_customer)(customer)
modeladmin.message_user(
request,
ngettext(
'%d customer was successfully synced.',
'%d customers were successfully synced.',
len(queryset),
) % len(queryset), messages.SUCCESS)
How can I fix this?
I use Version 5.1