我正试图允许用户喜欢特定帖子的评论。但是,当我尝试解决此问题时,不会发生预期的结果。
urls.py:
path('likecomment/<int:pk>/', post_views.likecomment,
name='likecomment'),
views.py:
def likecomment(request, pk):
if request.method == 'POST':
comment = get_object_or_404(Comment, pk=pk)
comment.likes += 1
comment.save()
return redirect('home')
comments.html:
{% for com in comments %}
<br>
<br>
<br>
<b>{{ com.user.username }}</b>   {{ com.body }}
<br>
<p class="text-muted">{{ com.pub_date_pretty }}    
      {{ com.likes }} Likes</p>
<a href="javascript:
{document.getElementById('likecomment').submit()}"> Like </a>
<form id="likecomment" method="post" action="{% url 'likecomment'
com.id %}">
{% csrf_token%}
<input type="hidden">
</form>
<br>
{% endfor %}
主视图:
@login_required(login_url='/login')
def home(request):
posts = Post.objects.all()
return render(request, 'posts/home.html', {'posts': posts})
呈现评论:
def comment(request, pk):
form = CommentForm()
comments = Comment.objects.filter(post__pk=pk)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = Comment()
comment.body = form.cleaned_data['body']
comment.user = request.user
comment.post = Post.objects.get(pk=pk)
comment.save()
return redirect('home')
else:
return render(request, 'posts/comments.html', {'error': 'Please submit valid data'})
else:
return render(request, 'posts/comments.html', {'form': form, 'comments': comments})
喜欢评论视图:
def likecomment(request, pk):
if request.method == 'POST':
comment = get_object_or_404(Comment, pk=pk)
comment.likes += 1
comment.save()
return redirect('home')
有时会发生类似的情况,但是没有正确的注释。该功能无法正常工作。
答案 0 :(得分:-1)
您有多个具有相同form
(id
)的HTML likecomment
元素。 Javascript无法知道您打算提交哪一个。尝试在{{ forloop.counter }}
值后附加一个唯一标识符,例如id
,例如:
<form id="likecomment-{{ forloop.counter }}" ...
和
document.getElementById('likecomment-{{ forloop.counter }}').submit()