persistent NOT NULL constraint failed: base_profile.user_id error

This is my register_user func in, as title suggests I cant register a profile bec of user_id not null constarint. I am beginner to the framework

def register_user(request):
    with transaction.atomic():
        user_serializer = UserSerializer(
        if user_serializer.is_valid():
            new_user =

            profile_data = {
                'user':,  # Pass user ID to the profile serializer
                'first_name':'first_name', ''),
                'last_name':'last_name', ''),
                'email':'email', '')

            profile_serializer = ProfileSerializer(data=profile_data)

                if profile_serializer.is_valid():
                    return Response(, status=status.HTTP_201_CREATED)
                    new_user.delete()  # Delete user if profile creation fails
                    return Response(profile_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
            except IntegrityError as e:
                print(f"Integrity Error: {e}")  # Print the integrity error
                new_user.delete()  # Delete user to avoid inconsistent data
                return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

this are my serializers in

from rest_framework import serializers
from base.models import *

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

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

class ProfileSerializer(serializers.ModelSerializer):
    user = UserSerializer(many=False, read_only=True)
    class Meta:
        model = Profile
        fields = ('user', 'first_name', 'last_name', 'email')

and this is the Profile Model:

from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    email = models.EmailField()
    class Meta:
        app_label = 'base'

    def __str__(self):
        return self.user.username

I’d appreciate it if you can point me out to the error i been using the react form to post a new user and debugging for nearly an hour but got to nothing.

The issue you are facing with the “NOT NULL constraint failed: base_profile.user_id” error indicates that you are trying to create a Profile instance without providing a value for the user field, which is a OneToOneField and is not allowed to be NULL . In your ProfileSerializer , you have user specified as read_only=True , meaning it won’t be used for input data.