【发布时间】:2020-04-25 21:32:06
【问题描述】:
我想请你帮忙。我想创建简单的投票系统。我不知何故成功了。我有一个简单的“UP”按钮,该按钮使用简单的 +1 整数作为帖子的得分值。它现在有很多问题,但我会与他们斗争。
现在我想在不刷新页面的情况下添加这个 +1 分数(就像大多数现代网站一样)。我进行了谷歌搜索,我想出了这个:https://www.codingforentrepreneurs.com/blog/ajaxify-django-forms/ 我不得不说它运行良好,即使我对 js、jquery 或 ajax 的知识为零。
我的问题是,javascript 添加了这个 +1,但它也给了我一些我无法理解的错误:
responseText: "TypeError at /viewquestion/6/voteup\n__init__() missing 1 required positional argument: 'data'\n\nRequest Method: POST\nRequest URL: http://127.0.0.1:8000/viewquestion/6/voteup\nDjango Version: 3.0.4\n
我想摆脱它们或了解它们的本质:P
我的第二个或主要问题是。投票正在进行,但分数不会改变,因为当然,页面没有重新加载。而且我也无法为用户打印“成功投票”消息,因为网站不刷新。
给用户一些简单的消息“投票成功”对我来说就足够了。最好的情况是立即更新分数,但我不知道这会让事情变得多么复杂。
您能帮我解决这个问题或指出正确的方向吗?因为我对 js/ajax 或 jquery 一无所知,所以即使有谷歌搜索的想法对我来说也很难。
这是我现在能做的:
base.html:
<script src="https://code.jquery.com/jquery-3.4.1.min.js" crossorigin="anonymous"></script>
<script>
// using jQuery
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('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);
}
}
});
</script>
views.py:
@login_required()
def questionvoteup(request, question_pk):
question = get_object_or_404(Question, pk=question_pk, user=request.user)
if request.is_ajax() and request.method == "POST":
question.votesscore += 1
question.amountofvotes += 1
question.save()
messages.success(request, 'Thank you for your vote!')
return JsonResponse()
else:
return HttpResponse(400, 'Invalid form')
home.html:
<ul>
{% for question in allquestionswithanswers %}
<li>
{{ question }} Score: {{ question.votesscore }} {{ question.user }}
{% if messages %}
{% for message in messages %}
{{ message }}
{% endfor %}
{% endif %}
<br><br>
<form class='my-ajax-form' method='POST' action='.' data-url="{% url 'questionvoteup' question.id %}" >
{% csrf_token %}
<button type='submit'>UP</button>
</form>
{% for answer in question.answer_set.all %}
{{ answer }}<br>
{% endfor %}
</li>
{% endfor %}
</ul>
谢谢。
【问题讨论】:
标签: javascript python jquery django ajax