Home > Software design >  Creating and updating Model object using form
Creating and updating Model object using form

Time:02-14

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?

CodePudding user response:

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()
  • Related