DRF Error: Cannot assign must be a instance


I’m working on an app that lets you track your expenses and I’m trying to create an ‘balnace’ object when the user registers, but when I try so I get an Error: Cannot assign "15": "Balance.user_id" must be a "Users" instance.


class Balance(models.Model):

balance = models.FloatField(
    verbose_name="Balance", blank=False, null=False)
user_id = models.ForeignKey(
    'expenseApi.Users', verbose_name="Usuario", blank=False, null=False, on_delete=models.PROTECT)

def __str__(self):
    return '{}'.format(self.pk)


class RegisterSerializer(serializers.ModelSerializer):

tokens = serializers.SerializerMethodField()
email = serializers.EmailField(max_length=50)
class Meta:
    model = Users
    fields= ['id', 'email', 'password', 'name', 'lastname', 'birthday', 'tokens']
    extra_kwargs = {
        'password': {
            'write_only': True,

def get_tokens(self,user):
        refresh = RefreshToken.for_user(user)

        data = {
            'refresh': str(refresh),
            'access': str(refresh.access_token),
        return data    

def create(self, request):

    email= Users.objects.filter(email=request['email'])

    if email:
        raise serializers.ValidationError({'detail': 'El email ya esta en uso'})

    user = Users.objects.create_user(email=request['email'],

    user['balance'] = Balance.objects.create(balance=0,user_id=user.id)

    return user


I didn’t go in detail about logic on your code but I guess error based on your code at

 user['balance'] = Balance.objects.create(balance=0,user_id=user.id)

should be

 user['balance'] = Balance.objects.create(balance=0, user_id=user)

Answered By – webbyfox

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published