pythondjangopostgresqldjango-rest-frameworkdjango-postgresql

Django postgress gives psycopg2.errors.NotNullViolation: null value in column "id_id" violates not-null constraint


Below is my model Windows 10, postgress 12, django 3.0.7, python 3.7.6

class User(AbstractBaseUser, PermissionsMixin):
    email = models.CharField(max_length=30)
    password = models.CharField(max_length=4000)

    first_name = models.CharField(default='', max_length=15)
    last_name = models.CharField(default='', max_length=15)
    login = models.CharField(max_length=15)
    age = models.IntegerField()
    street = models.CharField(blank=True, max_length=255)
    city = models.CharField(blank=True, max_length=255)
    zip = models.CharField(blank=True, max_length=10)
    role = models.CharField(default='', max_length=10)

    USERNAME_FIELD = 'email'

When I make a post request I'm getting below error

File "C:\Users\Akila\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.NotNullViolation: null value in column "id_id" violates not-null constraint
DETAIL:  Failing row contains (null, default).

This is the my signup view which is being called.

@staticmethod

@api_view(['POST'])

def sign_up(request):

    logging.debug("Trying to register a new user")

    data = common_methods.get_request_data(request)

    print(data)

    if check_user_exists(data['email']):

        return JsonResponse({'message': 'User with this email already exists'},status=status.HTTP_400_BAD_REQUEST)

    print(data['email'])

    create_user(data['email'], data['password'], data['fullName'])


    refresh = CustomTokenObtainPairSerializer.get_token(
        get_user_by_email(email=data['email']))
    return JsonResponse({'token': {
        'access_token': str(refresh.access_token),
        'expires_in': str(refresh.access_token.lifetime.seconds),
        'refresh_token': str(refresh)
    }})

Solution

  • Actially I had this in my create_user() method

     user_settings = UserSettings(id=user.id, theme='default')
     user.save()
     user_settings.save()
    

    As per above code user.id is null actually. id gets assigned AFTER user gets saved to database. had to change that to below to get it working correctly

    try:
        user.save()
    except Exception as e:
        print(str(e))
        raise Exception("Sorry couldn't save the user with email : " + user.email)
    
    if check_user_exists(user.email):
        user = get_user_by_email(email=user.email)
        user_settings = UserSettings(id_id=user.id, theme='default')
        user_settings.save()
    else:
        raise Exception("Sorry couldn't find the user with email : " + user.email)