# persistent NOT NULL constraint failed: base\_profile.user\_id error

**URL:** <https://forum.djangoproject.com/t/persistent-not-null-constraint-failed-base-profile-user-id-error/26406>\
**Category:** Mystery Errors\
**Created:** [December 24, 2023, 11:52pm UTC](https://forum.djangoproject.com/t/persistent-not-null-constraint-failed-base-profile-user-id-error/26406 "2023-12-24T23:52:47Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![muhamadtarek](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/muhamadtarek/32/17957_2.png) [@muhamadtarek](https://forum.djangoproject.com/u/muhamadtarek)\
**Post date:** [December 24, 2023, 11:52pm UTC](https://forum.djangoproject.com/t/persistent-not-null-constraint-failed-base-profile-user-id-error/26406/1 "2023-12-24T23:52:47Z")

</div>

This is my register\_user func in views.py, as title suggests I cant register a profile bec of user\_id not null constarint. I am beginner to the framework

```auto
@api_view(['POST'])
def register_user(request):
    with transaction.atomic():
        user_serializer = UserSerializer(data=request.data)
        
        if user_serializer.is_valid():
            new_user = user_serializer.save()
            print(new_user.id)

            profile_data = {
                'user': new_user.id, # Pass user ID to the profile serializer
                'first_name': request.data.get('first_name', ''),
                'last_name': request.data.get('last_name', ''),
                'email': request.data.get('email', '')
            }

            profile_serializer = ProfileSerializer(data=profile_data)

            try:
                if profile_serializer.is_valid():
                    print("profile")
                    profile_serializer.save()
                    return Response(user_serializer.data, status=status.HTTP_201_CREATED)
                else:
                    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 serializers.py:

```auto
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:

```auto
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.

---

<div class="post-metadata">

**Author:** ![addwebsolution](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/addwebsolution/32/23762_2.png) [@addwebsolution](https://forum.djangoproject.com/u/addwebsolution)\
**Post date:** [December 26, 2023, 9:16am UTC](https://forum.djangoproject.com/t/persistent-not-null-constraint-failed-base-profile-user-id-error/26406/2 "2023-12-26T09:16:28Z")

</div>

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.
