Home>

I'm studying django. I'm thinking of adding a comment function to write an impression on the posted Post model
in models.py

class Comment (models.Model):
    user = models.ForeignKey (settings.AUTH_USER_MODEL, on_delete = models.CASCADE, related_name ='comment_user')
    post = models.ForeignKey (Post, on_delete = models.CASCADE)
    date_created = models.DateTimeField (auto_now_add = True)
    text = models.TextField ()
    def __str __ (self):
        return self.text


And add to forms.py

class CommentForm (forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('text',
        )

in views.py

def comment (request, pk):
    if request.method == "POST":
        form = CommentForm (request.POST)
        if form.is_valid ():
            comment = form.save (commit = False)
            comment.user = request.user
            comment.date_created = timezone.now ()
            posts = Post.objects.filter (pk = pk)
            comment.post = posts.first ()
            comment.save ()
            return redirect ('post_detail', pk = posts.pk)
    else: else:
        form = CommentForm ()
    return render (request,'mybook/comment.html', {'form': form})


In the view, I intended to get the pk of the post page, save the comment for that post, and then move to the detail page (post_detail) of that post.
return redirect ('post_detail', pk = posts.pk)
By the way
'QuerySet' object has no attribute'pk'
I got the error.
I think it means that there is no pk in the original post (Query set) obtained by posts = Post.objects.filter (pk = pk), but I am in trouble because I do not know the cause. Thank you.

  • Answer # 1

    What if you do the following?

    def comment (request, pk):
        if request.method == "POST":
            form = CommentForm (request.POST)
            if form.is_valid ():
                comment = form.save (commit = False)
                comment.user = request.user
                Comment out because the # auto_add_now field is set automatically
                # comment.date_created = timezone.now ()
                #Changed to use model get method
                # posts = Post.objects.filter (pk = pk)
                # comment.post = posts.first ()
                comment.post = Post.objects.get (pk = pk)
                comment.save ()
                #QuerySet does not have a pk property, so use the model's pk property
                # return redirect ('post_detail', pk = posts.pk)
                return redirect ('post_detail', pk = comment.post.pk)
        else: else:
            form = CommentForm ()
        return render (request,'mybook/comment.html', {'form': form})