I am trying to solve this problem :
A user can add skills to his profile and other user can upvote the skill on his profile .
I have implemented adding skills in system . Now next I am trying build adding a skill (which is already added in system by admins ) to be added to the user profile .
But in my POST API , i am always getting following error
{
"user": {
"user": [
"This field is required."
]
}
}
Body Input :
{
"user":{
"username": "USERN",
"email": "diahu@gail.com",
"first_name": "",
"last_name": ""
},
"new_user_skill":
{
"id": 1,
"skill_name": "C"
}
}
My View :
elif request.method == 'POST':
data = { 'user':request.data.get('user'),'skill_item':request.data.get('new_user_skill')}
serializer = UserSkillSerializer(data=data)
print("-------------------> serializer ")
print(serializer)
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)
Model :
class UserModelSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email')
extra_kwargs = {
'username': {
'validators': [],
}
}
class UserProfileSerializer(serializers.ModelSerializer):
user=UserModelSerializer()
class Meta:
model = UserProfile
fields = '__all__'
def create(self, validated_data):
user_serializer = UserModelSerializer.create(UserModelSerializer(),validated_data = validated_data)
user,created=UserProfile.objects.update_or_create(user=user_serializer)
return user
class UserSkillSerializer(serializers.ModelSerializer):
user = UserProfileSerializer(required=True)
skill_item = SkillSerializer(required=True)
class Meta:
model = UserSkill
fields= '__all__'
def create (self,validated_data):
user_data = validated_data.pop('user')
user = UserProfileSerializer.create(UserProfileSerializer(),validated_data= user_data)
skill_data = validated_data.pop('skill_item')
skill_item = SkillSerializer.create(SkillSerializer(),validated_data=skill_data)
user_skill, created = UserSkill.objects.update_or_create(user=user,skill_item=skill_item)
return user_skill
Serializer :
class SkillSerializer(serializers.ModelSerializer):
class Meta:
model = Skill
fields = '__all__'
extra_kwargs = {
'skill_name': {
'validators': [],
}
}
class UserModelSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email')
extra_kwargs = {
'username': {
'validators': [],
}
}
class UserProfileSerializer(serializers.ModelSerializer):
user=UserModelSerializer()
class Meta:
model = UserProfile
fields = '__all__'
def create(self, validated_data):
user_serializer = UserModelSerializer.create(UserModelSerializer(),validated_data = validated_data)
user,created=UserProfile.objects.update_or_create(user=user_serializer)
return user
class UserSkillSerializer(serializers.ModelSerializer):
user = UserProfileSerializer(required=True)
skill_item = SkillSerializer(required=True)
class Meta:
model = UserSkill
fields= '__all__'
def create (self,validated_data):
user_data = validated_data.pop('user')
user = UserProfileSerializer.create(UserProfileSerializer(),validated_data= user_data)
skill_data = validated_data.pop('skill_item')
skill_item = SkillSerializer.create(SkillSerializer(),validated_data=skill_data)
user_skill, created = UserSkill.objects.update_or_create(user=user,skill_item=skill_item)
return user_skill
I have removed validators (not sure if that is correct approach )
Edit 1
I have edited much of my code as per answer (i have studied and implemented reverse relation ) , facing one Not Null constraint even though I have null=True
My Updated code :
Serializer :
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email','user_profile')
class UserSkillSerializer(serializers.ModelSerializer):
user = serializers.PrimaryKeyRelatedField(read_only=True)
skill_item = serializers.PrimaryKeyRelatedField(read_only=True)
class Meta:
model = UserSkill
fields= ('user', 'skill_item')
Views :
elif request.method == 'POST':
current_user = User.objects.get(pk=request.data.get('user')) # get the user key
user_profile_id = current_user.user_profile.pk # get the user profile from reverse relation in model
data = { 'user':user_profile_id,'skill_item':request.data.get('skill_id')}
serializer = UserSkillSerializer(data=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)
Model :
# This class will more or less map to a table in the database and defines the many to many relationship between user-skill, this is our intermediate model
class UserSkill(models.Model):
""" A Model for representing skill in user profile """
unique_together = (('user', 'skill_item'),)
user = models.ForeignKey('UserProfile',on_delete=models.CASCADE,related_name='current_user_skills')
skill_item = models.ForeignKey(Skill,on_delete=models.CASCADE,null=True)
def __str__(self):
"""Return a human readable representation of the model instance."""
return "{}".format(self.skill_item.skill_name)
# this class adds a Many to Many field in existing django-rest auth UserProfile class for user and his/her skills
class UserProfile(models.Model):
user = models.OneToOneField('auth.User',unique=True,on_delete=models.CASCADE,related_name='user_profile')
user_skills = models.ManyToManyField(
Skill,
through='UserSkill',
through_fields=('user','skill_item'),null=True
)
#create user profile signal handler
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
Error :
return func(*args, **kwargs) File "C:\code\django\wantedly\src\wantedly_webapp\views\AllViews.py", line
61, in user_skill_collection serializer.save()
IntegrityError at /api/v1/user/skills/ NOT NULL constraint failed: wantedly_webapp_userskill.skill_item_id
This error is generated because the
UserProfileSerializer
has auser
field that expects a whole user definition. In general I believe you mix the concepts "user profile" / "user" in your serializers, which creates confusion.Once you have created a
User
with its associatedUserProfile
and aSkill
, a way to add theSkill
to theUserProfile
is by selecting them by primary key:The POST data to assign a
Skill
to aUserProfile
would then be: