我尝试使用AJAX在我的Django应用程序中实现类似的功能但是,当我尝试这样做时,我得到了POST http://localhost:8000/forum/like/ 404 (Not Found)
。我想做的就是在喜欢列表中添加/删除用户而不刷新整个页面。
@require_POST
def toggle_like(request):
if request.method == "POST":
user = request.user
slug = request.POST.get('slug', None)
question = get_object_or_404(Question, slug=slug)
if question.likes.filter(id=user.id).exists():
question.likes.remove(user)
else:
question.likes.add(user)
context = {'likes-count': question.likes.count}
return HttpResponse(json.dump(context), content_type='application/json')
from django.urls import path
from . import views
app_name = 'forum'
urlpatterns = [
path('like/', views.toggle_like, name='toggle-like'),
]
{% block javascript %}
<script>
$('#like').click(() => {
$.ajax({
method: 'POST',
url: "{% url 'forum:toggle-like' %}",
data: {
'slug': $(this).attr('name'),
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
dataType: 'json',
success: (response) => {
alert(response.message);
},
error: (response, error) => {
alert(response.responseText);
}
})
})
</script>
{% endblock %}
{% block content %}
<p>Likes: {{ question.likes.count }} <input type="button" id="like" name="{{ question.slug }}" value="Like" /></p>
{% endblock %}