在尝试实现django-multiupload时不断获取integrityError

时间:2015-12-13 13:35:00

标签: python django django-models django-forms django-uploads

在尝试实现django-multiupload应用程序时,我不断收到以下integrityError:

列中的

空值" post_id"违反非空约束 DETAIL:失败的行包含(9,post_images / 1899987_718836594813781_835045800_n.jpg ,, null,null,null)。

我正在尝试允许我的用户将多张图片上传到帖子中。我认为我出错的地方是它可以在获得帖子ID之前保存。在我的观点中,我更改了form_valid,这可能也会影响它。

理想情况下,我想将picture_author和项目实例传递给每个图像,但是为了开始,我已经将它们设置为null以确定如何仅传递post实例。

我是编码新手django,所以任何帮助解决它都会非常感激!

模型:

class ProjectPost(models.Model):
    project = models.ForeignKey(UserProject)
    title = models.CharField(max_length=100)
    post_overview = models.CharField(max_length=1000)
    date_created = models.DateTimeField(auto_now_add=True)
    post_views = models.IntegerField(default=0)
    post_likes = models.IntegerField(default=0)
    post_author = models.ForeignKey(User, null=True)


class PostImages(models.Model):
    post_picture = models.FileField(upload_to='post_images', blank=True) 
    post = models.ForeignKey(ProjectPost)
    picture_description = models.CharField(max_length=100)
    picture_author = models.ForeignKey(User, null=True)
    project = models.ForeignKey(UserProject, null=True)

形式

class ProjectPostForm(forms.ModelForm):

    class Meta:
        model = ProjectPost
        fields = ('title', 'post_overview')

    files = MultiFileField(min_num=1, max_num=20, max_file_size=1024*1024*5)

    def save(self, commit=True):
        instance = super(ProjectPostForm, self).save(commit)
        for each in self.cleaned_data['files']:
            PostImages.objects.create(post_picture=each, post=instance)

        return instance

视图

class NewPost(CreateView):
    model = ProjectPost
    form_class = ProjectPostForm
    template_name = 'howdidu/new_post.html'

    def form_valid(self, form):
        self.object = form.save(commit=False)
        project = UserProject.objects.get(slug=self.kwargs["slug"])
        self.object.project = project
        form.instance.post_author = self.request.user
        self.object.save()
        return super(NewPost, self).form_valid(form)

    def get_success_url(self):
        project_username = self.request.user.username
        project_slug = self.object.project.slug
        return reverse('user_project', kwargs={'username':project_username, 'slug': project_slug})

1 个答案:

答案 0 :(得分:0)

您必须先保存帖子,然后才能向其中添加图片。在保存图像之前,你需要明确地告诉get_or_create post_id应该是什么,我不认为你在你的代码中这样做。