Django Rest Framework, How do I grab a foreign key value and add it to my serializer or view to create a new object?

models.py

User model it the import auth user model from django

class Profile(models.Model):
username_id = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
phone_number = PhoneNumberField(blank=True, null=True)
image_url = models.ImageField(blank=True, null=True)
address = models.CharField(max_length=30)
update = models.DateTimeField('Updated at', default=timezone.now())

def __str__(self):
    return self.username_id.__str__()

views.py

@api_view(['POST'])
def profile_create(request, pk):
    request
    serializer = ProfileCreateSerializer(data=request.data)
    # print(serializer)

    if serializer.is_valid():

        serializer.save()
    else:
        return Response(serializer.errors)
    return Response(serializer.data)

serializers.py

class ProfileCreateSerializer(serializers.ModelSerializer):

class Meta:
    model = Profile
    fields = ['phone_number', 'image_url', 'address']

I want to create a new profile for a user put I don’t know where or how to pass the foreign key value to the serializer or view to create a new profile

error

django.db.utils.IntegrityError: null value in column "username_id_id" of relation "users_pr
ofile" violates not-null constraint
DETAIL:  Failing row contains (, , HELLLfwfwefwf, 2021-09-02 20:08:58.53219+00, null).

Answer

Assuming the profile is for the currently logged in user, you can do something like this in your save():

serializer.save(username_id=request.user)

This will set username_id foreign key to the currently logged in user.