Django自定义用户模型中的IntegrityError,即使删除所有迁移后也不会消失

63lcw9qa  于 2023-06-25  发布在  Go
关注(0)|答案(2)|浏览(116)

每当我试图创建一个帖子时,我总是得到这个错误。我已经在这个平台上经历了所有类似的问题,并进行了几次调整,但错误仍然发生。
IntegrityError at /API/admin/create/ NOT NULL constraint failed:blog_post.author_id请求方法:POST请求URL:http://127.0.0.1:8000/api/admin/create/
下面是我的用户模型:

class NewUser(PermissionsMixin, AbstractBaseUser):

    email = models.EmailField(_('email_address'), unique=True)
    user_name = models.CharField(max_length=150, unique=True)
    first_name= models.CharField(max_length=150, blank=True)
    about = models.TextField(_('about'), max_length=500, blank=True)
    start_date = models.DateTimeField(default=timezone.now)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=True)

    objects = CustomAccountManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name', 'user_name']

下面是我的custome用户模型的自定义管理器:

class CustomAccountManager(BaseUserManager):

    def create_superuser(self, email, user_name, first_name, password, **other_fields):

        other_fields.setdefault('is_superuser', True)
        other_fields.setdefault('is_staff', True)
        other_fields.setdefault('is_active', True)

        if other_fields.get('is_superuser') is not True:
            raise ValueError('superuser must be assigned to is_superuser=True')
        if other_fields.get('is_staff') is not True:
            raise ValueError('superuser must be assigned to is_staff=True')

        user = self.create_user(email, user_name, first_name, password, **other_fields)
     
        user.save(using=self._db)
        return user

    def create_user(self, email, user_name, first_name, password, **other_fields):
        if not email:
            raise ValueError(_('You must provide an email address'))
        email = self.normalize_email(email)
        user = self.model(email=email, user_name=user_name, first_name=first_name, **other_fields)

        user.set_password(password)
        user.save()
        return user

下面是我的custome用户模型的序列化器类:

class RegisterUserSerializer(serializers.ModelSerializer):

    email = serializers.EmailField(required=True)
    username = serializers.CharField(required=True)
    password = serializers.CharField(min_length=8, write_only=True)

    
    class Meta:
        model = NewUser
        fields = ('email', 'user_name', 'password', 'first_name')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        password = validated_data.pop('password', None)
        instance = self.Meta.model(**validated_data)
        if password is not None:
            instance.set_password(password)
        instance.save()
        return instance

下面是我的观点:

class CustomUserCreate(APIView):
    permission_classes = [AllowAny]

    def post(self, request, format='json'):

        reg_serializer = RegisterUserSerializer(data=request.data)
        if reg_serializer.is_valid():
            newuser = reg_serializer.save()
            if newuser:
                json = reg_serializer.data
                return Response(json, status= status.HTTP_201_CREATED)
        return Response(reg_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

以下是端点“www.example.com”连接到的post视图http://127.0.0.1:8000/api/admin/create/:

class CreatePost(generics.CreateAPIView):
    permission_classes = [permissions.IsAuthenticated]
    queryset = Post.objects.all()
    serializer_class = PostSerializer

首次编辑:以下是帖子模型:

class Post(models.Model):
    class PostObjects(models.Manager):
        def get_queryset(self):
            return super().get_queryset().filter(status = 'published')
            
    options = (
        ('draft', 'Draft'),
        ('published', 'Published')
    )

    post_id = models.BigAutoField(primary_key=True)
    category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1, related_name="postcategory")
    title = models.CharField(max_length=250)
    excerpt = models.TextField(null=True)
    photo = models.ImageField(_("image"), upload_to=upload_to, default='posts/default.jpg')
    content = models.TextField()
    slug = models.SlugField(max_length=250, unique_for_date='published')
    published = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="blog_posts")
    status = models.CharField(max_length=10, choices=options, default='published')
    objects = models.Manager()      #default manager
    postobjects = PostObjects()     #custom manager

    class Meta:
        ordering = ('-published',)

    def __str__(self):
        return self.title

第二次编辑:下面是我在设置文件中的设置:

自定义用户模型

AUTH_USER_MODEL = "users.NewUser"

第三次编辑:这是我用来创建帖子的视图和序列化器:
查看

class CreatePost(generics.CreateAPIView):
    permission_classes = [permissions.IsAuthenticated]
    queryset = Post.objects.all()
    serializer_class = PostSerializer

串行化器:

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ('post_id', 'category', 'title', 'author', 'content', 'excerpt', 'slug', 'status', 'photo')
piwo6bdm

piwo6bdm1#

你能在你的数据中添加Post Model吗?也许我能帮上忙如果我看到它

gupuwyp2

gupuwyp22#

Post模型需要一个用户作为作者,但没有传递任何作者。这将导致“NOT NULL约束失败:blog_post.author_id”错误,因为author_id不能为null。要解决这个问题,请提供您用来创建帖子的视图和序列化程序。这将允许我演示如何将当前用户或发出请求的用户指定为作者(假设这是您的意图)。

编辑:

重写序列化程序的create方法,将作者设置为请求用户:

from rest_framework import serializers

class PostSerializer(serializers.ModelSerializer):
    def create(self, validated_data):
        validated_data['author'] = self.context['request'].user
        return super().create(validated_data)

    class Meta:
        model = Post
        fields = ('post_id', 'category', 'title', 'author', 'content', 'excerpt', 'slug', 'status', 'photo')

相关问题