gpt4 book ai didi

javascript - 投票功能 "No Eintrag matches the given query"

转载 作者:行者123 更新时间:2023-11-28 05:55:02 25 4
gpt4 key购买 nike

我想实现投票功能。投票函数无法获取对象。 vote.js 应该没问题。任何想法?看来 POST 请求没有发送。谢谢。

这是错误:

Page not found (404)
Request Method: GET
Request URL: http://.../vote/
Raised by: book.views.vote
No Eintrag matches the given query.

result.html 中的片段:

<a href="/vote/" id="eintrag-vote-{{ eintrag.id }}" class="vote">▲</a>
<p id="eintrag-title-{{ eintrag.id }}">{{ eintrag.title }}</p>

模型.py:

class Eintrag(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
title = models.CharField(max_length=200)
points = models.IntegerField(default=1)
text = models.TextField()

views.py:

@login_required
def vote(request):
eintrag = get_object_or_404(Eintrag, id=request.POST.get('eintrag'))
eintrag.points += 1
eintrag.save()
return HttpResponse()

url.py:

url(r'^vote/$', views.vote, name='vote'),

和 vote.js:

$(document).ready(function() {

// 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.vote(eintragID) {
$.ajax({
type: "POST",
url: "/vote/",
data: {
"eintrag": eintragID
},
success: function() {
$("#eintrag-vote-" + eintragID).hide();
$("#eintrag-title-" + eintragID).css({
"margin-left": "15px"
});
},
headers: {
'X-CSRFToken': csrftoken
}
});
return false;
}

$("a.vote").click(function() {
var eintragID = parseInt(this.id.split("-")[2]);
return vote(eintragID);
})

});

最佳答案

您的请求方法似乎不匹配。当您应该执行 POST 时,您却执行了 GET。

此行引发 404,因为没有 request.POST:

eintrag = get_object_or_404(Eintrag, id=request.POST.get('eintrag'))

我邀请您使用 django.views.decorators.http.require_POST 装饰此 View ,以便您收到更好地反射(reflect)方法问题的 HTTP 405 Method not allowed 错误比 404

我认为它来自于你的 Ajax 请求在 JS 中的完成方式(参见 http://api.jquery.com/jquery.ajax/ )

您可以尝试更改以下内容吗?

function vote(eintragID) {
$.ajax({
...

关于javascript - 投票功能 "No Eintrag matches the given query",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37776307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com