简体   繁体   中英

How can a logged in user comment on a post? django

I wrote the codes for commenting system and whenever you want to add a comment to a post, You'll be redirected to a page that you can write your comment and choose which member you are.

How can I fix the member field with the user that is currently logged in to the site?

And how can I make the comment section only down the post and not being redirected to another page?

Here's my view.py

def comment_post(request, slug):
    post = get_object_or_404(Post, slug=slug)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('samplepost', slug=post.slug)
    else:
        form = CommentForm()
    return render(request, 'blogapp/comment.html', {'form': form})

and here is my models.py

class Comment(models.Model):
    author = models.ForeignKey(User,on_delete=models.CASCADE, null=True)
    post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, related_name='comments')
    body = models.TextField()
    date_created = models.DateTimeField(auto_now_add=True)

"How can I fix the member field with the user that is currently logged in to the site?" - to access the current logged in user, use request.user in your Django template. This gives you the User object. If you have a username field in the User model, you can of course use request.user.username to get the username.

"And how can I make the comment section only down the post and not being redirected to another page?" - I'm assuming you mean placing the comment section below the post and posting comments without redirecting the page. For that, create the comment section as a textarea inside a form, place the element wherever you want using HTML and CSS, and use an AJAX request to post the form input to the backend.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM