“ user_id”列中的null值违反了非null约束详细信息:失败的行包含(此处为字段)

时间:2019-07-19 06:22:45

标签: django python-3.x django-models django-rest-framework

我正在使用jwt auth系统,当我填写该字段时,它会轻松返回jwt令牌,但是如果我想使用此令牌创建配置文件,则会引发以下错误

IntegrityError at /profile/
null value in column "user_id" violates not-null constraint
DETAIL:  Failing row contains (7, 2019-07-19 05:38:32.786263+00, 2019-07-19 05:38:32.786305+00, John, Doe, 2017-02-05 05:25:00+00, null, , England,english , native, null).

user / models.py

class CustomUser(AbstractBaseUser, PermissionsMixin):
  email = models.EmailField(max_length=40, unique=True)
  first_name = models.CharField(max_length=30, blank=True)
  last_name = models.CharField(max_length=30, blank=True)
  date_joined = models.DateTimeField(default=timezone.now)

  objects = UserManager()

  USERNAME_FIELD = 'email'

user / serializers.py

class UserSerializer(serializers.ModelSerializer):

date_joined = serializers.ReadOnlyField()

class Meta:
    model = CustomUser
    fields = ['id', 'email', 'first_name', 'last_name',
              'date_joined', 'password']
    extra_kwargs = {'password': {'write_only': True}}

user / views.py

class CreateUserAPIView(APIView):
     permission_classes = (AllowAny,)

def post(self, request):
    user = request.data
    serializer = UserSerializer(data=user)
    serializer.is_valid(raise_exception=True)
    serializer.save()

    try:
        email = request.data['email']
        password = request.data['password']

        user = CustomUser.object.get(email=email, password=password)
        if user:
            try:
                payload = jwt_payload_handler(user)
                token = jwt.encode(payload, settings.SECRET_KEY)
                user_details = {}
                user_details['id'] = "%s" % (user.id)
                user_details['token'] = token
                user_logged_in.send(sender=user.__class__,
                                    request=request, user=user)
                return Response(user_details, status=status.HTTP_200_OK)

            except Exception as e:
                raise e
        else:
            return Response(status=status.HTTP_403_FORBIDDEN)
    except KeyError:
        res = {'error': 'please provide a email and a password'}
        return Response(res)

使用此代码,我获得令牌,但无法创建配置文件 用于创建个人资料

models.py

class Profile(TimeModel):

   user = models.OneToOneField('user.CustomUser', on_delete=models.CASCADE)
   first_name = models.CharField(max_length=30, null=True)
   last_name = models.CharField(max_length=30, null=True)
   birthdate = models.DateTimeField(null=True)
   image = models.ImageField(upload_to='path', null=True)

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

我陷入了这个问题,该如何解决?顺便说一句,使用该令牌,我应该只创建一个配置文件,但是从错误DETAIL: Failing row contains (7,)可以看到,这里的id是7,但是我再次在邮递员中发送发布请求,它将是8,它应该抛出错误,例如Profile存在还是什么?预先感谢!

0 个答案:

没有答案