django null value in column violates not-null constraint postgres

Viewed 882

I am attempting to have a form that a user can upload multiple images on their blog. When the user submits the form I get the error null value in column "post_id" of relation "blog_postimages" violates not-null constraint The form has a foreign key to the blogpost. What confuses me is that the value is not null and I am using it else where (pk). I am running a postgres db

view

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)

models

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)

I do not have any unapplied migrations and I am positive I am calling it properly. Even if I hard code in a number it still errors out.

form

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

You should be updating the instance and not the form, so:

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

No need for test.save()

Related