''RegisterAPI' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method
I am trying to display a register_view here and I'm getting the error. I have made some changes to the views fil,e but i am still getting the errors and i don't know how to fix it. Here is my views.py file:
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework import generics, permissions
from knox.models import AuthToken
from .serializer import RegistrationSerializer
class RegisterAPI(generics.GenericAPIView):
user_serializer_class = RegistrationSerializer
def post(self, request, *args, **kwargs):
user_serializer = self.get_serializer(data=request.data)
data = {}
if user_serializer.is_valid():
user = user_serializer.save()
return Response({
"user": RegistrationSerializer(user, context=self.get_serializer_context()).data,
"token": AuthToken.objects.create(user)[1]
})
else:
data = user_serializer.error
return Response(data)
And here is what is in my serializer.py file:
from rest_framework.serializers import ModelSerializer, CharField
from rest_framework.serializers import ValidationError as Error
from django.contrib.auth.models import User
class RegistrationSerializer(ModelSerializer):
password2 = CharField(
style={'input_type': 'password'}, write_only=True)
class Meta:
model = User
fields = [
"username",
"email",
"password",
"password2"
]
extra_kwargs = {
'password': {'write_only': True}
}
def save(self):
user = User(
email=self.validated_data['email'],
username=self.validated_data['username']
)
password1 = self.validated_data['password1']
password2 = self.validated_data['password2']
if password1 != password2:
raise Error({'password': 'Passwords must match'})
user.set_password(password)
user.save()
return user
Solution 1:[1]
you need to use serializer_class
attribute instead of user_serializer_class
class RegisterAPI(generics.GenericAPIView):
serializer_class = RegistrationSerializer
Solution 2:[2]
You need to change
class RegisterAPI(generics.GenericAPIView):
to
class RegisterAPI(APIView):
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sohaib |
Solution 2 | Konstantin |