question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Error: SynchronousOnlyOperation with Django 3

See original GitHub issue

I have Ubuntu 18.04. I’ve followed the instructions in the README, but when I run python manage.py livereload and open localhost:8000 I get a SynchronousOnlyOperation error. My traceback is as follows. It seems to raise error at {% user.is_authenticated %} template tag.

Environment:


Request Method: GET
Request URL: http://localhost:8000/

Django Version: 3.1
Python Version: 3.6.9
Installed Applications:
['livereload',
 'formsapp',
 'Dummy',
 'crispy_forms',
 'users',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'allauth',
 'allauth.account',
 'allauth.socialaccount',
 'allauth.socialaccount.providers.facebook',
 'allauth.socialaccount.providers.github',
 'allauth.socialaccount.providers.google']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']


Template error:
In template /home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/formsapp/templates/forms/base.html, error at line 18
   You cannot call this from an async context - use a thread or sync_to_async.
   8 :     <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
   9 : 
   10 :     <title>{% block title %}Home page{% endblock %}</title>
   11 :     <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
   12 :     <link rel="stylesheet" href="{% static 'css/styles.css' %}">
   13 : </head>
   14 : <body>
   15 : <header>
   16 :     <div>
   17 :         <!-- User login/logout options -->
   18 :          {% if user.is_authenticated %} 
   19 :             <a href="{% url 'logout' %}">Sign out</a>
   20 :         {% else %}
   21 :             <a href="{% url 'login' %}">Sign In</a>
   22 :             <a href="{% url 'register' %}">Sign Up</a>
   23 :         {% endif %}
   24 :         User: {{ user }}
   25 :     </div>
   26 :     <h1>
   27 :         <a id="logo" href="{% url 'home-page' %}">Website name & logo</a>
   28 :     </h1>


Traceback (most recent call last):
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py", line 215, in _get_session
    return self._session_cache

During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred:
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/formsapp/views.py", line 10, in show_homepage
    return render(request, 'forms/base.html')
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/shortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/template/loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/template/base.py", line 170, in render
    return self._render(context)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/template/base.py", line 162, in _render
    return self.nodelist.render(context)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/template/base.py", line 938, in render
    bit = node.render_annotated(context)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/template/base.py", line 905, in render_annotated
    return self.render(context)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/template/defaulttags.py", line 305, in render
    match = condition.eval(context)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/template/defaulttags.py", line 889, in eval
    return self.value.resolve(context, ignore_failures=True)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/template/base.py", line 671, in resolve
    obj = self.var.resolve(context)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/template/base.py", line 796, in resolve
    value = self._resolve_lookup(context)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup
    current = current[bit]
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/utils/functional.py", line 240, in inner
    self._setup()
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/utils/functional.py", line 376, in _setup
    self._wrapped = self._setupfunc()
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/contrib/auth/middleware.py", line 23, in <lambda>
    request.user = SimpleLazyObject(lambda: get_user(request))
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/contrib/auth/middleware.py", line 11, in get_user
    request._cached_user = auth.get_user(request)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/contrib/auth/__init__.py", line 174, in get_user
    user_id = _get_user_session_key(request)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/contrib/auth/__init__.py", line 58, in _get_user_session_key
    return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY])
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py", line 65, in __getitem__
    return self._session[key]
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py", line 220, in _get_session
    self._session_cache = self.load()
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/db.py", line 43, in load
    s = self._get_session_from_db()
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/db.py", line 34, in _get_session_from_db
    expire_date__gt=timezone.now()
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/db/models/query.py", line 425, in get
    num = len(clone)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/db/models/query.py", line 269, in __len__
    self._fetch_all()
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/db/models/query.py", line 1303, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/db/models/query.py", line 53, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1152, in execute_sql
    cursor = self.connection.cursor()
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/utils/asyncio.py", line 24, in inner
    raise SynchronousOnlyOperation(message)

Exception Type: SynchronousOnlyOperation at /
Exception Value: You cannot call this from an async context - use a thread or sync_to_async.

My project structure is as follows:

.
├── db.sqlite3
├── Dummy
├── formsapp
├── manage.py
├── mental_health_app
├── my-cred.txt
├── __pycache__
├── README.md
├── requirements.txt
├── users
├── venv

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:2
  • Comments:6

github_iconTop GitHub Comments

1reaction
lingstercommented, Apr 2, 2021

I had a similar problem and managed to work around as per suggestion here: https://docs.djangoproject.com/en/3.1/topics/async/#async-safety ie defined an environment variable: DJANGO_ALLOW_ASYNC_UNSAFE=1

note this should only be done in a local non-production/development environment or you could risk losing/corrupting data.

In my case I am running a project created using django 3.1.7 and python 3.8.8

0reactions
pradyunsgcommented, Feb 3, 2022

You really shouldn’t be using livereload in production.

Read more comments on GitHub >

github_iconTop Results From Across the Web

SynchronousOnlyOperation Error in with django 3 and django ...
I had a django 2 app and i used django channels for socket connection. i just update django to version 3. and now...
Read more >
[Solved]-SynchronousOnlyOperation Error in with django 3 ...
I have opened an issue for django channels about updating docs. @database_sync_to_async def get_user(token_key): try: return Token.objects.get(key=token_key).
Read more >
SynchronousOnlyOperation exception if request.user is not ...
ASGI/ASYNC SessionMiddleware - SynchronousOnlyOperation exception if ... print(user) except SynchronousOnlyOperation: print('error 3') # CASE 4 try: user ...
Read more >
[Django] #32798: StreamingHttpResponse raises ...
#32798: StreamingHttpResponse raises SynchronousOnlyOperation in ASGI server ... This error is probably caused by the fact that Django 3 now actively
Read more >
SynchronousOnlyOperation and DatabaseError in multiple ...
I'm unable to reproduce the problem on my staging or local environment, ... I'm using the gunicorn==20.0.4 and Django==3.2.6 . ... 3 mo....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found