Hey everyone, I'm currently working on creating a user via API using nested serializers in Django Rest Framework and running into some issues. Here's the code snippet:
class AffiliateRegisterSerializer(serializers.ModelSerializer):
class Meta:
model = Affiliate
fields = ('phone', 'address', 'state', 'city', 'ZIP', 'country', 'company', 'web_name', 'web_url', 'web_desc', 'payee_name', 'monthly_visits',)
And here's my second serializer:
class UserSerializer(serializers.ModelSerializer):
'''
Registering a new user with Affiliate Profile
'''
affiliate = AffiliateRegisterSerializer(required=False)
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password', 'affiliate',)
write_only_fields = ('password',)
read_only_fields = ('id', 'affiliate',)
def create(self, validated_data):
affiliate_data = validated_data.pop('affiliate')
user = User.objects.create_user(**validated_data)
Affiliate.objects.create(user=user, **affiliate_data)
return user
Now, moving on to the view:
class AffiliateSignUp(generics.CreateAPIView):
'''
API endpoint for Affiliate Users registration
'''
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [permissions.AllowAny]
@method_decorator(ensure_csrf_cookie)
@method_decorator(csrf_protect)
def create(self, request):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
I'm looking to send a POST request via AngularJS to instantly create the user and profile. How can I accomplish this?
When attempting to POST a nested object via AngularJS, I encounter the following error message:
Affiliate field is required.
While registering the user directly through the backend works fine by visiting /api/affilaite URL, the challenge lies in sending the POST request with a nested object in JavaScript. Any insights on how to tackle this would be greatly appreciated.
Here is the excerpt of my javascript code:
data:$httpParamSerializerJQLike({
'first_name':$scope.userData['first_name'],
'last_name':$scope.userData['last_name'],
'username':$scope.userData['username'],
'password':$scope.userData['password'],
'email':$scope.userData['email'],
affiliate:{
'phone':$scope.userData['phone'],
'address':$scope.userData['address'],
'state':$scope.userData['state'],
'city':$scope.userData['city'],
'ZIP':$scope.userData['ZIP'],
'country':$scope.userData['country'],
'company':$scope.userData['company'],
'web_url':$scope.userData['webUrl'],
'web_name':$scope.userData['webName'],
'web_desc':$scope.userData['webDesc'],
//'web_category':$scope.userData ['webCategory'],
'payee_name':$scope.userData['payeeName'],
'monthly_visits':$scope.userData['monthly_visits']
}
}
I need your help on this matter, any advice or suggestions are welcome! Thank you :)