我有一个模型帖子,用户可以在其中留下评论和一组评分。我想限制每个帖子的用户评论只有一个。在我看来,我很难把它设置好
模型
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视图中的整个表单代码包装在某种类型的验证系统中,该系统检查当前登录的用户是否已经在该特定帖子上留下了评论(请参阅评论)。
有人知道潜在的解决方案是什么吗?或者如果我这样做的话?
发布于 2017-09-06 19:18:17
一种可能的解决办法是:
Post注释request.user过滤注释类似于:
from django.core.exceptions import PermissionDenied
def add_comment(request, slug):
post = get_object_or_404(Post, slug=slug)
# Get the comments posted by the user for this post
user_comments = post.comments.filter(user=request.user)
if request.method == 'POST':
form = CommentForm(request.POST or None)
# Check if there are any comments posted by the user
if user_comments:
# If there are any, raise an error
raise PermissionDenied('You have already commented on this post.')
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
}
return render(request, template, context)当然,您可以在这里修改引发的错误,但是主要的想法是获取注释并通过request.user对它们进行筛选,并查看是否存在。
https://stackoverflow.com/questions/46082573
复制相似问题