Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating and updating Model object using form

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading