I have a problem with Ajax and Django templates. I'm new to Ajax and jquery.
Console log at the end of the script prints undefined. I don't know why let 
answerid = $(this).attr("answer-id"); doesn't extract attribute from this 
line: <i class="upvote" answer-id="{{answer.id}}">&#8593</i> 
I also want to know if using template tags in javascript scripts like here $
.post("{% url 'upvote' %}", {answer_id:answerid}) is a good idea.


{% extends 'base.html' %}
{% block title %}{{question.title|truncatechars:52}}{% endblock %}
{% block content %}
<h1>{{question.title}}</h1>
<p>{{question.content}}</p>
{% for answer in question.answers.all %}
<h3>{{answer.author}}</h3>
<p>{{answer.content}}</p>
<p>
<i class="upvote" answer-id="{{answer.id}}">&#8593</i>
{{answer.votes.count}}
<i class="downvote" answer-id="{{answer.id}}">&#8595</i>
</p>
{% endfor %}
<form method="POST" action="{% url 'answer' question.id %}">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Odpowiedz">
</form>
{% endblock %}
{% block javascript %}
{% load static %}
<script src=
"https://cdn.jsdelivr.net/npm/js-cookie@rc/dist/js.cookie.min.js";></script>
<script>
//upvote and downvote script
var csrftoken = window.Cookies.get('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$(".upvote").click( () => {
let answerid = $(this).attr("answer-id");
console.log(answerid);
$.post("{% url 'upvote' %}", {answer_id:answerid});
});
</script>
{% endblock %}

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/aa129ea5-dd3d-402f-a297-796b408e8217%40googlegroups.com.

Reply via email to