0

I keep getting the following integrityError when trying to implement the django-multiupload app:

null value in column "post_id" violates not-null constraint DETAIL: Failing row contains (9, post_images/1899987_718836594813781_835045800_n.jpg, , null, null, null).

I am trying to allow my users to upload multiple pictures to a post. I think where I am going wrong is that it may be saving before being able to get the post id. In my views I have changed the form_valid which may also be effecting it.

Ideally I would like to pass the picture_author and project instances to each image as well, but to get started I have put them = null to figure out how to pass just the post instance at the moment.

Im new to coding & django, so any help in trying to solve it would be much appreciated!

models:

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)

forms

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

views

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})
ollysmall
  • 633
  • 2
  • 7
  • 13

1 Answers1

0

You have to save the post before you can add images to it. You need to explicitly tell the get_or_create what the post_id is supposed to be before an image will be saved, and I dont think you're doing that in your code.