尝试实现 django-multiupload 应用程序时,我不断收到以下完整性错误:
“post_id”列中的空值违反非空约束细节:失败行包含(9,post_images/1899987_718836594813781_835045800_n.jpg,,null,null,null)。
我试图让我的用户将多张图片上传到帖子中。我认为我出错的地方是它可能会在获得帖子ID之前进行保存。在我看来,我已经更改了 form_valid,这也可能对其产生影响。
理想情况下,我也想将 picture_author 和 project 实例传递给每个图像,但开始时我已经将它们设置为 = 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})