尝试将数据发布到Django API时,NOT NULL约束失败



我有一个包含两个应用程序的项目;React应用程序用于前端,Django应用程序用于后端。

我在React中建立了我的注册页面,在Django中建立了注册过程。我想将两者连接起来,使用户能够浏览我创建的注册页面,并根据用户提交的信息创建用户。

这是我的型号.py

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=100, blank=True)
location = models.CharField(max_length=100, blank=True)
password = models.CharField(max_length=32)
email = models.EmailField(max_length=150)
signup_confirmation = models.BooleanField(default=False)
def __str__(self):
return self.user.username
@receiver(post_save, sender=User)
def update_profile_signal(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()

Serializers.py:

class ProfileSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Profile
fields = ('user_id', 'name', 'location', 'password', 'email', 'signup_confirmation')

以及React 中的POST功能

const onSubmit = e => {
e.preventDefault();
const user = {
email: email,
name: name,
location: 'Example',
password: password,
user_id: 1,
};
console.log(user);
fetch('http://127.0.0.1:8000/api/v1/users/profiles/?format=api', {
method: 'POST',
headers: {
'Content-Type':'application/json'
},
body: JSON.stringify(user)
})
.then(res => res.json())
.then(data => {
if (data.key) {
localStorage.clear();
localStorage.setItem('token',data.key);
window.location.replace('http://localhost:3000/profile/');
} else {
setEmail('');
setName('');
setPassword('');
localStorage.clear();
setErrors(true);
}
});
};

问题是当我试图创建一个用户时;我在Django 中收到这个错误消息

django.db.utils.IntegrityError: NOT NULL constraint failed: accounts_profile.user_id

当我检查我的网络检查器时,我得到一条CCD_ 1消息。在进一步检查时(将进行预览(;我看到这个

IntegrityError at /api/v1/users/profiles/
NOT NULL constraint failed: accounts_profile.user_id

我还检查了如果我在fetch((中控制台日志res.text,我会得到什么,这就是我得到的:

<!DOCTYPE html>
<html>
<head>


<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="robots" content="NONE,NOARCHIVE" />

<title>Profile List – Django REST framework</title>
...

关于我可能会出错的地方,有什么想法吗?

我应该更仔细地阅读标题。这并不是说你违反了一个唯一的约束,而是说你传递的值为null。

我会先把你的一对一关系改为ForeignKey关系。

接下来,您需要首先实际创建用户,然后才能为该用户分配配置文件。

我还将删除电子邮件和密码字段,并依靠内置的用户模型和功能来创建您的用户。

最新更新