在 django 中创建新用户时的 NOT NULL 约束

发布于 2025-01-11 12:16:34 字数 1798 浏览 0 评论 0原文

我创建了一个 Django API 来创建新用户。但是,当我尝试创建用户时,收到错误消息:

IntegrityError at /api/v1/users/register/ NOT NULL约束失败:accounts_user.user_id

这是我在 models.py 中的内容

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class User(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:
        User.objects.create(user=instance)
    instance.profile.save()

在serializers.py

from rest_framework import serializers
from .models import User

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

和我的views.py

from rest_framework import viewsets
from .serializers import UserSerializer
from .models import User
from rest_framework.decorators import action


from .forms import SignUpForm
from .tokens import account_activation_token

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all().order_by('name')
    serializer_class = UserSerializer

    @action (detail=True, methods=['post'])
    def register(self, request):
        print(request)

中关于我可以做什么来解决此错误的任何想法

I created a Django API to create a new user. However, when I try to create a user I get the error message:

IntegrityError at /api/v1/users/register/ NOT NULL constraint failed: accounts_user.user_id

This is what I have in models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class User(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:
        User.objects.create(user=instance)
    instance.profile.save()

In serializers.py

from rest_framework import serializers
from .models import User

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

and my views.py

from rest_framework import viewsets
from .serializers import UserSerializer
from .models import User
from rest_framework.decorators import action


from .forms import SignUpForm
from .tokens import account_activation_token

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all().order_by('name')
    serializer_class = UserSerializer

    @action (detail=True, methods=['post'])
    def register(self, request):
        print(request)

Any ideas on what I can do to resolve this error

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

故人的歌 2025-01-18 12:16:34

正如约翰在评论中写道:
这里有一个问题:fields = ('user_id',...)

我还建议您更改您的 User 模型。如果您不需要分离(我想您不需要),那么最好直接从 AbstractUser 继承来创建您的 User ,而不是实际上创建双倍的 <代码>用户模型。

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    ...

通过这种方式,您将已经拥有用户名密码电子邮件,但您可以在同一模型中添加任何其他内容,而不是使用user.user

As John wrote in a comment:
Here you have a problem: fields = ('user_id',...).

I also advise you to change your User model. If you don't need separating (I suppose you don't), it is way better to create your User with inheritance directly from AbstractUser instead of creating in fact doubled User models.

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    ...

In this way you will already have username, password and email, but you can add anything else in same model, instead of using user.user etc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文