Django: SynchronousOnlyOperation: You cannot call this from an async context – use a thread or sync_to_async

The error occurs because Jupyter notebooks has a running event loop.
From documentation

If you try to run any of these parts from a thread where there is a running event loop, you will get a SynchronousOnlyOperation error. Note that you don’t have to be inside an async function directly to have this error occur. If you have called a synchronous function directly from an asynchronous function without going through something like sync_to_async() or a threadpool, then it can also occur, as your code is still running in an asynchronous context.

If you encounter this error, you should fix your code to not call the offending code from an async context; instead, write your code that talks to async-unsafe in its own, synchronous function, and call that using asgiref.sync.sync_to_async(), or any other preferred way of running synchronous code in its own thread.

If you are absolutely in dire need to run this code from an asynchronous context – for example, it is being forced on you by an external environment, and you are sure there is no chance of it being run concurrently (e.g. you are in a Jupyter notebook), then you can disable the warning with the DJANGO_ALLOW_ASYNC_UNSAFE environment variable.

As the question is specific to jupyter notebook environment following is a valid solution.

import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rest.settings')
os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"
django.setup()
    
from users.models import User
User.objects.all()

One need to however by wary and not use it in production environment as per documentation warnings.

Leave a Comment