I am trying to register a reader (extended django User model) making a post request from python client. I have provided the user data while making a post request from a python client to 'reader-register'. Still I am getting this error: {'user': ['This field is required.']}. But it works fine from browsable API of django rest framework.
Here are the relevant codes.
class ReaderSerializer(serializers.ModelSerializer):
user = UserSerializer(required=True)
class Meta:
model = Reader
fields = ['user', 'photo_url', 'bio']
def create(self, validated_data):
print(self.initial_data)
user_data = validated_data.pop('user')
user = User.objects.create(**user_data)
reader = Reader.objects.create(user=user, **validated_data)
return reader
def update(self, instance, validated_data):
user_data = validated_data.pop('user')
user = instance.user
user.username = user_data.get('username', user.username)
user.email = user_data.get('email', user.email)
user.first_name = user_data.get('first_name', user.first_name)
user.last_name = user_data.get('last_name', user.last_name)
user.save()
instance.photo_url = validated_data.get(
'photo_url', instance.photo_url)
instance.bio = validated_data.get('bio', instance.bio)
instance.save()
return instance
UserSerializer
class UserSerializer(serializers.ModelSerializer):
email = serializers.EmailField(
required=True,
validators=[UniqueValidator(queryset=User.objects.all())]
)
class Meta:
model = User
fields = ['username', 'password',
'email', 'first_name', 'last_name']
extra_kwargs = {
'password': {
'write_only': True,
'required': True,
},
'first_name': {
'required': True,
},
'last_name': {
'required': True,
},
'username': {
'required': True,
},
}
APIView
class ReaderRegisterAPIView(CreateAPIView):
serializer_class = ReaderSerializer
permission_classes = [AllowAny]
python client
import requests
data = {
"user": {
"username": "a",
"email": "[email protected]",
"first_name": "test",
"last_name": "test",
"password": "a"
},
"photo_url": "",
"bio": ""
}
endpoint = 'http://localhost:8000/api/reader/register/'
response = requests.post(endpoint, data=data)
What am I missing here?
CodePudding user response:
Send the request with json
parameter:
data = {...}
response = requests.post(endpoint, json=data)
Django REST Framework by default accepts application/json
as a content-type, while data
parameter sends the body as application/x-www-form-urlencoded