Issue
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.
Model
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)
serializer
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'],
password=request['password'],
name=request['name'],
lastname=request['lastname'],
birthday=request['birthday'])
user['balance'] = Balance.objects.create(balance=0,user_id=user.id)
return user
Solution
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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.