Django postgress 给出 psycopg2.errors.

下面是我的模型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'

当我发出发布请求时,出现以下错误


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).

这是被调用的我的注册视图。


@静态方法


@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)

    }})


慕后森
浏览 100回答 1
1回答

小唯快跑啊

实际上我在 create_user() 方法中有这个 user_settings = UserSettings(id=user.id, theme='default') user.save() user_settings.save()根据上面的代码 user.id 实际上是 null 。id 在用户保存到数据库后被分配。必须将其更改为下面才能使其正常工作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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python