我使用django默认用户模型创建了UserExtended模型,用于存储用户的额外详细信息,这样我就可以存储额外的用户数据,并在需要时调用它们
这是型号
class UserExtended(models.Model):
extended_id = models.AutoField(primary_key=True, editable=False)
avatar = models.ImageField(null=True, blank=True)
user = models.OneToOneField(User, on_delete=models.CASCADE, null=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
视图功能是:
@api_view(['GET'])
def get_user_profile(request):
user = request.user
serializer = UserSerializer(user, many=False)
return Response(serializer.data)
序列化程序:
class UserSerializer(serializers.ModelSerializer):
name = serializers.SerializerMethodField(read_only=True)
isAdmin = serializers.SerializerMethodField(read_only=True)
avatar = serializers.ImageField(source=UserExtended.avatar, read_only=True)
class Meta:
model = User
fields = ['id', 'username', 'email', 'name', 'avatar', 'isAdmin']
def get_name(self, obj):
name = obj.first_name
if name == '':
name = obj.email
return name
def get_isAdmin(self, obj):
return obj.is_staff
我想我应该得到一个像这样的api响应
GET http://localhost:8000/api/users/profile
HTTP/1.1 200 OK
Date: Mon, 14 Jun 2021 13:45:13 GMT
Server: WSGIServer/0.2 CPython/3.9.2
Content-Type: application/json
Vary: Accept
Allow: OPTIONS, GET
X-Frame-Options: DENY
Content-Length: 103
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
{
"id": 1,
"username": "superuser",
"email": "superuser@test.com",
"name": "superuser@test.com",
"avatar": "/images/Capture.PNG"
"isAdmin": true
}
不工作但是我得到了这个错误请帮我解决
GET http://localhost:8000/api/users/profile
HTTP/1.1 500 Internal Server Error
Date: Mon, 14 Jun 2021 13:48:50 GMT
Server: WSGIServer/0.2 CPython/3.9.2
Content-Type: text/plain; charset=utf-8
X-Frame-Options: DENY
Content-Length: 21746
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
TypeError at /api/users/profile
argument of type 'ImageFileDescriptor' is not iterable
Request Method: GET
Request URL: http://localhost:8000/api/users/profile
Django Version: 3.2.4
Python Executable: D:work environmentDjango_ApicodersavvyScriptspython.exe
Python Version: 3.9.2
Python Path: ['D:\work environment\Django_Api\codersavvy', 'C:\Users\S\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\S\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\S\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\S\AppData\Local\Programs\Python\Python39', 'D:\work environment\Django_Api\codersavvy', 'D:\work environment\Django_Api\codersavvy\lib\site-packages']
Server time: Mon, 14 Jun 2021 13:48:50 +0000
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'blog.apps.BlogConfig']
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 "D:work environmentDjango_Apicodersavvylibsite-packagesdjangocorehandlersexception.py", line 47, in inner
response = get_response(request)
File "D:work environmentDjango_Apicodersavvylibsite-packagesdjangocorehandlersbase.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:work environmentDjango_Apicodersavvylibsite-packagesdjangoviewsdecoratorscsrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "D:work environmentDjango_Apicodersavvylibsite-packagesdjangoviewsgenericbase.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "D:work environmentDjango_Apicodersavvylibsite-packagesrest_frameworkviews.py", line 509, in dispatch
response = self.handle_exception(exc)
File "D:work environmentDjango_Apicodersavvylibsite-packagesrest_frameworkviews.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "D:work environmentDjango_Apicodersavvylibsite-packagesrest_frameworkviews.py", line 480, in raise_uncaught_exception
raise exc
File "D:work environmentDjango_Apicodersavvylibsite-packagesrest_frameworkviews.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "D:work environmentDjango_Apicodersavvylibsite-packagesrest_frameworkdecorators.py", line 50, in handler
return func(*args, **kwargs)
File "D:work environmentDjango_Apicodersavvyblogviews.py", line 32, in get_user_profile
return Response(serializer.data)
File "D:work environmentDjango_Apicodersavvylibsite-packagesrest_frameworkserializers.py", line 548, in data
ret = super().data
File "D:work environmentDjango_Apicodersavvylibsite-packagesrest_frameworkserializers.py", line 246, in data
self._data = self.to_representation(self.instance)
File "D:work environmentDjango_Apicodersavvylibsite-packagesrest_frameworkserializers.py", line 500, in to_representation
for field in fields:
File "D:work environmentDjango_Apicodersavvylibsite-packagesrest_frameworkserializers.py", line 361, in _readable_fields
for field in self.fields.values():
File "D:work environmentDjango_Apicodersavvylibsite-packagesdjangoutilsfunctional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:work environmentDjango_Apicodersavvylibsite-packagesrest_frameworkserializers.py", line 349, in fields
for key, value in self.get_fields().items():
File "D:work environmentDjango_Apicodersavvylibsite-packagesrest_frameworkserializers.py", line 1034, in get_fields
extra_kwargs, hidden_fields = self.get_uniqueness_extra_kwargs(
File "D:work environmentDjango_Apicodersavvylibsite-packagesrest_frameworkserializers.py", line 1389, in get_uniqueness_extra_kwargs
model_fields = self._get_model_fields(
File "D:work environmentDjango_Apicodersavvylibsite-packagesrest_frameworkserializers.py", line 1472, in _get_model_fields
if '.' in source or source == '*':
请帮我解决
您应该使用SerializerMethodField
。
avatar = serializers.SerializerMethodField()
def get_avatar(self, obj):
return obj.userextended.avatar.url
class Meta:
model = User
fields = ['id', 'username', 'email', 'name', 'avatar', 'isAdmin']