0
我一直試圖實現Django的multiupload應用程序時,得到以下integrityError:的愈來愈integrityError試圖執行時Django的multiupload
列「POST_ID」空值違反非空約束 詳細信息:如果不排包含(9,post_images/1899987_718836594813781_835045800_n.jpg,null,null,null)。
我想讓我的用戶上傳多張圖片到帖子。我認爲我出錯的地方在於它可能在獲得帖子ID之前進行保存。在我看來,我已經改變了form_valid,這也可能會影響它。
理想情況下,我希望將picture_author和項目實例傳遞給每個圖像,但要開始,我已經將它們設置爲null來弄清楚此刻如何傳遞post實例。
Im新編碼& 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})