[英]How can a logged in user comment on a post? django
我編寫了評論系統的代碼,每當您想向帖子添加評論時,您都會被重定向到一個頁面,您可以在該頁面上寫評論並選擇您是哪個成員。
如何使用當前登錄站點的用戶修復成員字段?
以及如何使評論部分僅在帖子下方而不被重定向到另一個頁面?
這是我的 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})
這是我的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)
“如何使用當前登錄站點的用戶修復成員字段?” - 要訪問當前登錄的用戶,請在 Django 模板中使用request.user
。 這為您提供了 User 對象。 如果您在 User 模型中有一個 username 字段,您當然可以使用request.user.username
來獲取用戶名。
“我怎樣才能讓評論部分只在帖子下方而不被重定向到另一個頁面?” - 我假設您的意思是將評論部分放在帖子下方並發布評論而不重定向頁面。 為此,將評論部分創建為表單內的文本區域,使用 HTML 和 CSS 將元素放置在您想要的任何位置,並使用 AJAX 請求將表單輸入發布到后端。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.