Home > database >  Django Rest Framework - Post more info User from Foreign Key
Django Rest Framework - Post more info User from Foreign Key

Time:05-18

I am new to Django Rest Framework and checked some tutorials. Now I am trying to create my own user profile with more fields like: company name, phone, ....I created OneToOneField (one-to-one relationship) table with more info for my extend user. Now i want to create new user with all fields in post method, but i got error. How can i fix this?

models.py

class MoreInfo(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    compName = models.CharField(max_length=100)
    title = models.CharField(null=True,max_length=128)
    birthday = models.DateField(null=True, blank=True)
    phone = models.CharField(max_length=20,blank=True)

api/serializer.py

class MoreInforSerializer(serializers.ModelSerializer):
   class Meta:
       model = MoreInfo
       fields = '__all__'
class CreateUserSerializer(serializers.ModelSerializer):
   moreInfoUser = MoreInforSerializer()
   class Meta:
      model = User
      fields = '__all__'
      extra_kwargs = {'password':{'write_only':True}}
   def create(self,validated_data):
      user = User.objects.create(
      email=validated_data['email'],
      username = validated_data['username'],
      password = make_password(validated_data['password'])
    )
    info_data = validated_data.pop('moreInfoUser')
    moreInfo = MoreInfo.objects.create(
        user = user,
        compName = info_data['compName'],
        title = info_data['title'],
        birthday = info_data['birthday'],
        phone = info_data['phone']
    )
    # user.save()
    return user

views.py

class ListCreateUser(ListCreateAPIView):
    serializer_class = CreateUserSerializer
    def post(self, request, *args, **kwargs):

       serializer = CreateUserSerializer(data=request.data)

       if serializer.is_valid():
           serializer.save()

            return JsonResponse({
               'message': 'Create a new Info successful!'
            }, status=status.HTTP_201_CREATED)

        return JsonResponse({
           'message': 'Create a new Info unsuccessful!'
        }, status=status.HTTP_400_BAD_REQUEST)

urls.py

path('createUser',views.ListCreateUser.as_view()),

POST:

{
   "username":"user5",
   "password":"12345aA@",
   "email":"[email protected]",
   "compName":"A",
   "title":"test",
   "birthday":"1997-05-04",
   "phone":"01234567"
}

Table for create User enter image description here

Errors: Can't create new User

Bad Request: /createUser
"POST /createUser HTTP/1.1" 400 46

CodePudding user response:

You have to upload moreInfoUser also because you set that in the serializer.

{
   "username":"user5",
   "password":"12345aA@",
   "email":"[email protected]",
   "compName":"A",
   "title":"test",
   "birthday":"1997-05-04",
   "phone":"01234567",
   "moreInfoUser": {
        "compName": "...",
        "title": "...",
        "birthday": "...",
        "phone": "..."
   }
}

Hope it could help.

  • Related