0

models.py

class PostModel(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date_time = models.DateTimeField(auto_now_add=True)
    title = models.TextField(null=True)
    body = models.TextField(null=True)
    def __str__(self):
        return str(self.user)

class ImagesPostModel(models.Model):
    post = models.ForeignKey(PostModel, on_delete=models.CASCADE)
    images = models.ImageField(null=True, blank=True)

views.py

def post(request):
    post = PostModel(user=request.user)
    post.save()
    if request.method == 'POST':
        form = PostModelForm(request.POST, instance=post)
        images = request.FILES.getlist('images')
        for image in images:
            ImagesPostModel.objects.create(post=post, images=image)
        if form.is_valid():
            form.save()
        return redirect('/Blog/home/')
    else:
        form = PostModelForm(request.POST)
        return render(request, 'post.html', {'form': form})

I created a PostModel object post and save it in the database using save() method. I have provided the instance parameter as post object in the form, so the form should be updating the above created post but it is creating another PostModel object and inserting into the database by itself. So there are two post begin created and being inserted into the database, first one is because of post = PostModel(user=request.user) and I dont know why the second one is being created. why is this happening?

1 Answer 1

1

The problem is the first 2 lines in the view

post = PostModel(user=request.user)
post.save()

As they create a PostModel obj with user=currentuser

To add the post to the user do the following rather than form.save()

post = form.save(commit=False)
post.user = request.user
post.save()
Sign up to request clarification or add additional context in comments.

3 Comments

A user can have any number of posts. What should I do then?
Check Updated answer
Please accept the answer to close the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.