Почему не работает ajax в django?
Форма:
<form class="form" action="{% url 'articles:send_comment' article.id %}" method="post">
{% csrf_token %}
<textarea id="text-comment" name="text" required="" placeholder="Напишите свой комментарий..." cols="30" rows="10"></textarea>
<div class="button-form"><button class="btn-form" id="send-comment" type="submit">Отправить</button></div>
</form>
Ajax:
<script>
var token = '{{csrf_token}}';
$('#send-comment').click(function(){
$.ajax({
url: 'send_comment/',
type: "POST",
dataType: "text",
data: {
'comment-text': $('#text-comment').val(),
},
headers: {
"X-Requested-With": "XMLHttpRequest",
"X-CSRFToken": token,
},
success: function(data){
console.log(1);
},
error: function(error){
console.log(1);
}
});
});
</script>
Views:
def send_comment(request, article_id):
if request.method == 'POST':
comment_text = request.POST['comment-text']
article = get_object_or_404(Article, id=article_id)
article.comment_set.create(comment_text=comment_text)
return HttpResponse("Success!")
else:
return HttpResponse("Request method is not a POST")
Urls:
app_name = 'articles'
urlpatterns = [
path('<int:article_id>/', views.detail, name='detail'), # Страница с новостью
path('<int:article_id>/send_comment', views.send_comment, name='send_comment')
]
Ошибка:
KeyError: 'comment-text'
comment_text = request.POST['comment-text']
В этой строке. Я пытался уже всё сделать даже отправлять через json, но там он присылался пустым. В консоли не выводится 1.
Нужно поменять путь на path('send_comment', views.send_comment, name='send_comment')
И соответственно в ajax тоже