Object of type leave is not JSON serializable

{i am unable to get how to resolve this problem.i am trying to save a dict buy creating a model instance but i am getting error due to the foreign key in my leave model which is connected to hostel manager through one to many relation }

i have resolved this error but got new error Object of type leave is not JSON serializable i do not how to resolve this

and in my database the data i obtain through request is getting saved but the data which i got from other table by using jwt token is not getting saved

final_data= leave(**serializer)

views.py

class leaveview(APIView):
    def post(self,request):
        token = request.data['jwt']
        if not token:
            raise AuthenticationFailed('Unauthenticated')
        
        try:
            payload = jwt.decode(token,'secret',algorithms=['HS256'])
        except jwt.ExpiredSignatureError:
            raise AuthenticationFailed('Unauthenticated')
        
        user=User.objects.filter(id=payload['id']).first()
        serializer1=UserSerializers(user).data


        serializer2 = leaveSerializers(data=request.data)
        serializer2.is_valid(raise_exception=True)
        serializer={**serializer1,**request.data}
        
        del serializer["jwt"]
        loc = hostel_manager.objects.get(hostel = serializer['hostel_name'])
        del serializer['hostel_name']
        del serializer['password']
        a=leave.objects.create(**serializer,**{'hostel_name' : loc} )
        
        
        a=leaveSerializers(a)
        return Response(a.data)

models.py


class hostel_manager(models.Model):
    hostel = models.CharField(max_length=100,primary_key=True)


class leave(models.Model):
    name=models.CharField(max_length=100,null = True)
    father_name=models.CharField(max_length=100,null=True)
    
    
    branch=models.CharField(max_length=40,null=True)
    coer_id=models.CharField(max_length=12,unique=True,null=True)
    
    hostel_name = models.ForeignKey(hostel_manager,on_delete=models.CASCADE)
    room_no = models.CharField(max_length=10)
    where_to = models.CharField(max_length=100)
    reason = models.CharField(max_length=300)
    start_date = models.CharField(max_length = 100,null=True)
    end_date = models.CharField(max_length=100,null=True)
    phone_regex=RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+9999999999'. Up to 12 digits allowed.")
    phone_number = models.CharField(validators=[phone_regex], max_length=17)

this is the error i got

  File "d:\python\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type leave is not JSON serializable

serializer.py

class leaveSerializers(serializers.ModelSerializer):
    class Meta:
        model = leave
        fields = ['id','hostel_name','room_no','where_to','reason','phone_number','start_date','end_date','name','father_name','branch','coer_id']


class hostelmanagerSerializers(serializers.ModelSerializer):
    class Meta:
        model = hostel_manager
        fields = ['hostel']

1 answer

  • answered 2021-09-28 02:34 Chris

    Error message suggests that you are trying to assign hostel_name as a string/CharField. As per your model, it needs to be a hostel_manager object.

    Not sure what your POST serializer or payload looks like but you'd probably want to set the hostel_manager_pk field to the kund kund bhawan's object's PK.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum