0
我有一個模型帖子,用戶可以在該帖子中留下評論以及一組評級。我想將用戶評論限制在每個帖子只有一個。我無法設置,在我的觀點django-forms:允許登錄用戶每個帖子只提交一條評論
車型
class Comment(models.Model):
post = models.ForeignKey(Post, related_name="comments")
user = models.ForeignKey(User, related_name="usernamee")
...
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
class Post(models.Model):
...
意見
def add_comment(request, slug):
post = get_object_or_404(Post, slug=slug)
# I tried wrapping all of the below in an "if" statement, something like
# if request.user.comment.exists(): to check if the user has already
# left a comment on this specific post, but I'm not sure of the right way to perform such a check here.
if request.method == 'POST':
form = CommentForm(request.POST or None)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.user = request.user
comment.email = request.user.email
comment.picture = request.user.profile.profile_image_url()
comment.save()
messages.success(request, "Thank you for leaving a review!")
return redirect('blog:post_detail', slug=post.slug)
else:
messages.error(request, "Something went wrong! We weren't able to process your review :(")
else:
form = CommentForm()
template = "blog/post/add_comment.html"
context = {
'form': form,
'post': post,
#'comment_count': comment_count
}
return render(request, template, context)
我的印象是,所有我需要是從包裹整個表單代碼在我add_comment視圖在某種驗證系統中檢查當前登錄用戶是否已經在該特定帖子上留言(請參閱評論)
任何人都知道可能的解決方案是什麼?或者,如果我甚至以正確的方式做這件事?
謝謝!我需要的只是'user_comments = post.comments.filter(user = request.user)'。我在if語句中封裝了我的整個表單請求,以便如果用戶已經離開審閱,那麼它甚至不會讓他們訪問add_comment表單頁面。思考這件事很容易,但對於我的生活,我無法弄清楚如何獲得用戶是否評論過的信息。再次感謝!! – dmandres
@dmandres不客氣! – wencakisa