简体   繁体   中英

TypeError: Object of type DeferredAttribute is not JSON serializable

While testing my project, I found this weird error: Object of type DeferredAttribute is not JSON serializable...

Before jump into the error, I want to tell what I wanted: Step 1: Registered User share his/her refer code so other person. Step 2: Unregistered person enters the code in the link. Step 3: The browser shows the button to continue to create account

This is urls.py file

from django.contrib import admin
from django.urls import path, include

from core import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.home),
    path('<str:code>/', views.home),
    path('accounts/', include('accounts.urls')),
    # path('', include('accounts.urls')),
]

This is views.py file

from django.shortcuts import render

from accounts.models import Refer

def home(request, *args, **kwargs):
    code = str(kwargs.get('code'))
    try:
        user = Refer.objects.get(referral_code = code)
        print(user.referral_code)
        request.session['ref_profile'] = Refer.id
        print('id', user.id)
    except:
        pass
    print(request.session.get_expiry_date())
    return render(request, 'accounts/registration.html')

A simple home.html file

{% extends 'base.html' %}

{% block title %}
home
{% endblock title %}

{% block bodycontent %}


{% if user.is_authenticated %}
    {{user}}
{% else %}
<p>
    "Hello Everyone"
</p> 
<button class="btn btn-primary"><a href="{% url 'accounts:registration' %}">Create New User</a></button>
{% endif %}
{% endblock bodycontent %}

After returning the statement of the print in the terminal

de829fab192047
id 1
2022-01-24 05:40:09.783734+00:00
Internal Server Error: /de829fab192047/
Traceback (most recent call last):

I got this on the web-page

Request Method: GET
Request URL: http://127.0.0.1:8000/de829fab192047/

Django Version: 4.0.1
Python Version: 3.10.0
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'accounts']
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']



Traceback (most recent call last):
  File "C:\Users\avins\Desktop\PyProjects\Web-Proj\Django\Personal\vkosh\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\avins\Desktop\PyProjects\Web-Proj\Django\Personal\vkosh\venv\lib\site-packages\django\utils\deprecation.py", line 128, in __call__
    response = self.process_response(request, response)
  File "C:\Users\avins\Desktop\PyProjects\Web-Proj\Django\Personal\vkosh\venv\lib\site-packages\django\contrib\sessions\middleware.py", line 59, in process_response
    request.session.save()
  File "C:\Users\avins\Desktop\PyProjects\Web-Proj\Django\Personal\vkosh\venv\lib\site-packages\django\contrib\sessions\backends\db.py", line 83, in save
    obj = self.create_model_instance(data)
  File "C:\Users\avins\Desktop\PyProjects\Web-Proj\Django\Personal\vkosh\venv\lib\site-packages\django\contrib\sessions\backends\db.py", line 70, in create_model_instance
    session_data=self.encode(data),
  File "C:\Users\avins\Desktop\PyProjects\Web-Proj\Django\Personal\vkosh\venv\lib\site-packages\django\contrib\sessions\backends\base.py", line 91, in encode
    return signing.dumps(
  File "C:\Users\avins\Desktop\PyProjects\Web-Proj\Django\Personal\vkosh\venv\lib\site-packages\django\core\signing.py", line 135, in dumps
    return TimestampSigner(key, salt=salt).sign_object(obj, serializer=serializer, compress=compress)
  File "C:\Users\avins\Desktop\PyProjects\Web-Proj\Django\Personal\vkosh\venv\lib\site-packages\django\core\signing.py", line 183, in sign_object
    data = serializer().dumps(obj)
  File "C:\Users\avins\Desktop\PyProjects\Web-Proj\Django\Personal\vkosh\venv\lib\site-packages\django\core\signing.py", line 112, in dumps
    return json.dumps(obj, separators=(',', ':')).encode('latin-1')
  File "C:\Users\avins\anaconda3\envs\djlab\lib\json\__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "C:\Users\avins\anaconda3\envs\djlab\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Users\avins\anaconda3\envs\djlab\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:\Users\avins\anaconda3\envs\djlab\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '

Exception Type: TypeError at /de829fab192047/
Exception Value: Object of type DeferredAttribute is not JSON serializable

In the home view you try to store a model field definition ( Refer.id ) instead of the retrieved object's actual id value. Just replace Refer with user on the second line:

    user = Refer.objects.get(referral_code = code)
    request.session['ref_profile'] = user.id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM