gpt4 book ai didi

python - Django REST 框架 : AttributeError: 'DeferredAttribute' object has no attribute 'isoformat'

转载 作者:行者123 更新时间:2023-12-04 10:13:24 25 4
gpt4 key购买 nike

这是我第一次使用 Django REST FRAMEWORK,我遇到了注册 api 的问题,第一次尝试时 api 工作正常,但在接下来的尝试中,它开始抛出此错误

AttributeError: 'DeferredAttribute' object has no attribute 'isoformat'



首先这是我的代码:
序列化程序.py:
class UserSerializer(serializers.ModelSerializer):

def create(self, validated_data):
user = User.objects.create(**validated_data)
user.set_password(validated_data['password'])
user.save()
# return dict(status=True, code=1)
return User

class Meta:
model = User
fields = ['phone', 'email', 'first_name', 'last_name', 'birth_date', 'gender', 'user_type', 'password',
'username']
extra_kwargs = {
"password": {"write_only": True}
}

api.py:
class RegisterApi(CreateAPIView):
model = get_user_model()
permission_classes = [permissions.AllowAny]
serializer_class = UserSerializer

模型.py:
class User(AbstractUser):

notification_token = models.CharField(max_length=255, unique=True, blank=True, null=True)
phone = models.CharField(
_("Phone Number"),
max_length=50,
validators=[phone_validator],
unique=True,
)
is_active = models.BooleanField(
_('active'),
default=False,
help_text=_(
'Designates whether this user should be treated as active. '
'Unselect this instead of deleting accounts.'
),
)
photo = models.ImageField(
_('Profile Picture'),
upload_to='profile/',
help_text=_(
"the user's profile picture."
),
blank=True,
null=True
)
address = models.CharField(_("Address"), max_length=255)
lives_in = models.ForeignKey('City', on_delete=do_nothing, null=True, blank=True)
user_type = models.CharField(
_("Type"),
max_length=3,
choices=USER_TYPES,
help_text=_("The user's type can be one of the available choices, "
"refer to the Model class for the detailed list."),
)
birth_date = models.DateField(_('Birth Date'), blank=True, null=True)
gender = models.CharField(choices=GENDERS, max_length=1, default='M')

USERNAME_FIELD = "username"

REQUIRED_FIELDS = ["first_name", "last_name", 'user_type', 'phone', 'email']

@property
def get_age(self) -> int:
today = date.today()
dob = self.birth_date
before_dob = (today.month, today.day) < (dob.month, dob.day)
return today.year - self.birth_date.year - before_dob

@property
def confirmed_phone(self) -> bool:
return False

@property
def confirmed_email(self) -> bool:
return False

def __str__(self):
return self.phone

现在当我发布 this

我收到此错误:
Internal Server Error: /api/register/
Traceback (most recent call last):
File "C:\Users\Simou\Desktop\Work\IT-GDS\Resto\web\restaurant\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Simou\Desktop\Work\IT-GDS\Resto\web\restaurant\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Simou\Desktop\Work\IT-GDS\Resto\web\restaurant\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Simou\Desktop\Work\IT-GDS\Resto\web\restaurant\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\Simou\Desktop\Work\IT-GDS\Resto\web\restaurant\venv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Simou\Desktop\Work\IT-GDS\Resto\web\restaurant\venv\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "C:\Users\Simou\Desktop\Work\IT-GDS\Resto\web\restaurant\venv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\Simou\Desktop\Work\IT-GDS\Resto\web\restaurant\venv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "C:\Users\Simou\Desktop\Work\IT-GDS\Resto\web\restaurant\venv\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\Simou\Desktop\Work\IT-GDS\Resto\web\restaurant\venv\lib\site-packages\rest_framework\generics.py", line 190, in post
return self.create(request, *args, **kwargs)
File "C:\Users\Simou\Desktop\Work\IT-GDS\Resto\web\restaurant\venv\lib\site-packages\rest_framework\mixins.py", line 20, in create
headers = self.get_success_headers(serializer.data)
File "C:\Users\Simou\Desktop\Work\IT-GDS\Resto\web\restaurant\venv\lib\site-packages\rest_framework\serializers.py", line 562, in data
ret = super().data
File "C:\Users\Simou\Desktop\Work\IT-GDS\Resto\web\restaurant\venv\lib\site-packages\rest_framework\serializers.py", line 260, in data
self._data = self.to_representation(self.instance)
File "C:\Users\Simou\Desktop\Work\IT-GDS\Resto\web\restaurant\venv\lib\site-packages\rest_framework\serializers.py", line 529, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "C:\Users\Simou\Desktop\Work\IT-GDS\Resto\web\restaurant\venv\lib\site-packages\rest_framework\fields.py", line 1327, in to_representation
return value.isoformat()
AttributeError: 'DeferredAttribute' object has no attribute 'isoformat'

知道用户正在数据库中注册,但响应抛出此错误。
任何帮助表示赞赏。

最佳答案

您应该返回 user来自 create() 的实例方法,而不是 User类(class):

class UserSerializer(serializers.ModelSerializer):

def create(self, validated_data):
user = User.objects.create(**validated_data)
user.set_password(validated_data['password'])
user.save()
# return dict(status=True, code=1)
return user # instead of User

关于python - Django REST 框架 : AttributeError: 'DeferredAttribute' object has no attribute 'isoformat' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61204850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com