列中的 django 空值违反了非空约束 postgres

django null value in column violates not-null constraint postgres

我正在尝试创建一个表单,用户可以在其博客上上传多张图片。当用户提交表单时,我收到错误 null value in column "post_id" of relation "blog_postimages" violates not-null constraint 表单有指向博文的外键。令我困惑的是该值不为空,我在其他地方 (pk) 使用它。我是 运行 一个 postgres db

查看

def DetailPostView(request, pk):
    model = Post
    post = Post.objects.get(pk=pk)

    if request.method == 'POST':
        test = PostImagesForm(request.POST, request.FILES)
        files = request.FILES.getlist('images')
        if test.is_valid():
            for f in files:
                test.save(commit=False)
                test.post = Post.objects.get(pk=pk)
                test.save()
        else:
            print(PostImagesForm.errors)
             

    context = {
        'post':post, 'PostImagesForm':PostImagesForm,
        }
    return render(request, 'blog/post_detail.html', context)

型号

class Post(models.Model):
    title = models.CharField(max_length=100)
    image = models.ImageField(default='default.jpg', upload_to='hero_car_image')
    content = RichTextUploadingField(blank=True, null=True)
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

class PostImages(models.Model):
    post = models.ForeignKey('Post', on_delete=models.CASCADE)
    images = models.ImageField(upload_to='post_images')
    date_posted = models.DateTimeField(default=timezone.now)

我没有任何未应用的迁移,我确信我正在正确调用它。即使我硬编码一个数字,它仍然会出错。

形式

class PostImagesForm(ModelForm):
    class Meta:
        model = PostImages
        fields = ('images',)
        widgets = {
            'images': forms.ClearableFileInput(attrs={'multiple': True}),
        }

您应该更新实例而不是表单,因此:

instance = test.save(commit=False)
instance.post = Post.objects.get(pk=pk)
instance.save()

不需要test.save()