The field was declared on serializer , but has not been included error in django rest
我在DjangoRESTAPI中创建了一些序列化程序,并陷入了奇怪的问题。当我访问
Environment:
Request Method: GET Request URL: http://localhost:8000/api/users/
Django Version: 1.10.2 Python Version: 3.5.2 Installed Applications:
['django.contrib.admin', 'django.contrib.auth',
'django.contrib.contenttypes', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.staticfiles',
'rest_framework', 'api'] 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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']Traceback:
File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages\django\core\handlers\exception.py"
in inner
39. response = get_response(request)File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages\django\core\handlers\base.py"
in _legacy_get_response
249. response = self._get_response(request)File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages\django\core\handlers\base.py"
in _get_response
217. response = self.process_exception_by_middleware(e, request)File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages\django\core\handlers\base.py"
in _get_response
215. response = response.render()File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages\django\template
esponse.py"
in render
109. self.content = self.rendered_contentFile
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages
est_framework
esponse.py"
in rendered_content
72. ret = renderer.render(self.data, accepted_media_type, context)File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages
est_framework
enderers.py"
in render
697. context = self.get_context(data, accepted_media_type, renderer_context)File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages
est_framework
enderers.py"
in get_context
630. raw_data_post_form = self.get_raw_data_form(data, view, 'POST', request)File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages
est_framework
enderers.py"
in get_raw_data_form
553. content = renderer.render(serializer.data, accepted, context)File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages
est_framework\serializers.py"
in data
508. ret = super(Serializer, self).dataFile
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages
est_framework\serializers.py"
in data
244. self._data = self.get_initial()File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages
est_framework\serializers.py"
in get_initial
387. for field in self.fields.values()File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages
est_framework\serializers.py"
in fields
340. for key, value in self.get_fields().items():File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages
est_framework\serializers.py"
in get_fields
947. field_names = self.get_field_names(declared_fields, info)File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages
est_framework\serializers.py"
in get_field_names
1046. serializer_class=self.class.nameException Type: AssertionError at /api/users/ Exception Value: The
field 'photos' was declared on serializer UserSerializer, but has not
been included in the 'fields' option.
号
但我的用户序列化程序甚至没有"photos"字段。我是刚来Django的,请帮助我了解这个问题的根源。
序列化程序.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | from django.utils import timezone from django.contrib.auth.models import User from rest_framework import serializers from api.models import Album, Photo class PhotoSerializer(serializers.HyperlinkedModelSerializer): #url = serializers.HyperlinkedIdentityField(view_name="photo-detail") album = serializers.HyperlinkedRelatedField(view_name='album-detail', queryset=Album.objects) owner = serializers.HyperlinkedRelatedField(view_name='user-detail', queryset=User.objects) class Meta: model = Photo fields = ('url', 'name', 'image', 'creation_date', 'owner', 'album') read_only_fields=('creation_date') class AlbumSerializer(serializers.HyperlinkedModelSerializer): #url = serializers.HyperlinkedIdentityField(view_name="album-detail") owner = serializers.HyperlinkedRelatedField(view_name='user-detail', queryset=User.objects) photos = serializers.HyperlinkedRelatedField(view_name='photo-list', queryset=Photo.objects, many=True) def get_validation_exclusions(self): # Need to exclude `author` since we'll add that later based off the request exclusions = super(AlbumSerializer, self).get_validation_exclusions() return exclusions + ['user'] class Meta: model = Album fields = ('pk', 'name', 'creation_date', 'owner', 'photos') read_only_fields=('creation_date') class UserSerializer(serializers.HyperlinkedModelSerializer): #url = serializers.HyperlinkedIdentityField(view_name="user-detail", read_only=True) albums = serializers.HyperlinkedRelatedField(many=True, view_name='album-list', queryset=Album.objects) password = serializers.CharField(write_only=True, required=True) confirm_password = serializers.CharField(write_only=True, required=True) class Meta: model = User fields = ('url', 'pk', 'username', 'email', 'password', 'is_staff', 'albums') write_only_fields = ('password') read_only_fiels = ('pk') def create(self, validated_data): user = User.objects.create( username=validated_data['username'], email=validated_data['email'], ) user.set_password(validated_data['password']) user.save() return user def update(self, instance, validated_data): user = super(UserSerializer, self).update(instance, validated_data) user.set_password(validated_data['password']) user.save() return user def validate(self, data): if data['password']: if data['password'] != data['confirm_password']: raise serializers.ValidationError( "The passwords have to be the same" ) return data |
AuthRegister视图
1 2 3 4 5 6 7 8 9 10 | class AuthRegister(APIView): serializer_class = UserSerializer permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) |
号
api/urls.py版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | from django.conf.urls import include, url from .views import AuthRegister from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_token from rest_framework import routers from api import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'albums', views.AlbumViewSet) router.register(r'photos', views.PhotoViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^login/', obtain_jwt_token), url(r'^token-refresh/', refresh_jwt_token), url(r'^token-verify/', verify_jwt_token), url(r'^register/$', AuthRegister.as_view()), |
最后我找到了我愚蠢错误的根源。原因是我之前在我的模型中有一个摄影场。但是在模型中做了更改之后,我忘记了进行迁移。