Type Error: Field 'id' expected a number but got <User: ILador>

Question:

I am working with Django models and Django-Rest-Framework. When I try to access the models through the Rest-Framework I get "TypeError at /home/profiles/: Field ‘id’ expected a number but got <User: ILador>."

here’s my code:

Models.py-

from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MaxValueValidator, MinValueValidator
from datetime import date
from .countries import COUNTRIES



class Profile(models.Model):

    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def username(self):
        usern = User.objects.get(id=self.user)
        usern = usern.username
        return usern

    setup = models.BooleanField(default=False)
    dob = models.DateField()

    def age(self):
        today = date.today()
        age = today.year - self.birthday.year - ((today.month, today.day) < (self.birthday.month, self.birthday.day))
        return age

    orgin = models.CharField(max_length=300, choices=COUNTRIES)
    lives = models.CharField(max_length=300, choices=COUNTRIES)
    bio = models.CharField(max_length=150)
    email = models.CharField(max_length=255)
    hobbies = models.CharField(max_length=225)
    image = models.ImageField(upload_to='images')

Serializers.py-


from rest_framework import serializers
from .models import Profile
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields =('id', 'username', 'password')
        extra_kwargs = {'password': {'write_only': True, 'required': True}}

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        Token.objects.create(user=user)
        return user


class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields=( 'id', 'username','email', 'setup', 'dob', 'age', 'orgin', 'lives', 'bio', 'hobbies', 'image',)

Why am I getting this error?

Asked By: Itay Lador

||

Answers:

    def username(self):
        usern = User.objects.get(id=self.user) # <--
        usern = usern.username
        return usern

Here’s the error: self.user is an instance of User class, change this code line to use it’s id property usern = User.objects.get(id=self.user.id)

UPD: You probably don’t even need this .get(...) method, just:

    def username(self):
        return self.user.username
Answered By: svfat