I created few serializers in my django REST API and stuck with weird problem. When i go to the http://127.0.0.1:8000/api/register/
url i'm gets the error:
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\response.py" in render 109. self.content = self.rendered_content
File "D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages\rest_framework\response.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\rest_framework\renderers.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\rest_framework\renderers.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\rest_framework\renderers.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\rest_framework\serializers.py" in data 508. ret = super(Serializer, self).data
File "D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages\rest_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\rest_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\rest_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\rest_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\rest_framework\serializers.py" in get_field_names 1046. serializer_class=self.class.name
Exception Type: AssertionError at /api/users/ Exception Value: The field 'photos' was declared on serializer UserSerializer, but has not been included in the 'fields' option.
But my UserSerializer doesn't even have 'photos' field. I'm new in django, please, help me to understand source of this problem.
serializers.py
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 view
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
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()),