簡體   English   中英

如何在Django中添加評論喜歡系統

[英]How to add a comment liking system in Django

我試圖允許用戶喜歡特定帖子的評論。 但是,當我嘗試解決此問題時,不會發生預期的結果。

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> &nbsp {{ com.body }}
<br>
<p class="text-muted">{{ com.pub_date_pretty }} &nbsp   &nbsp   
&nbsp  &nbsp  &nbsp  {{ 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')

有時會發生類似的情況,但是沒有正確的注釋。 該功能無法正常運行。

圖片1 圖片1

圖片2: 在此處輸入圖片說明

您有多個具有相同idlikecomment )的HTML form元素。 Javascript無法知道您打算提交哪一個。 嘗試在id值后附加一個唯一標識符,例如{{ forloop.counter }} ,例如:

<form id="likecomment-{{ forloop.counter }}" ...

document.getElementById('likecomment-{{ forloop.counter }}').submit()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM