royaIT royaIT - 5 months ago 12
Ajax Question

vote-function "No Eintrag matches the given query"

I want to implement a vote function. The vote function can't get the object. vote.js should be okay. Any idea? Thank you.

This is the error:

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


snippet in result.html:

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


models.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()


urls.py:

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


and 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);
})

});



Answer

It seems you have a request method mismatch. You are doing a GET when you should be doing a POST.

This line raises a 404 because there is no request.POST:

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

I invite you to decorate this view with django.views.decorators.http.require_POST so you get an HTTP 405 Method not allowed error that better reflects the method issue than a 404

I think it comes from how your Ajax request is done in JS (see http://api.jquery.com/jquery.ajax/)

Can you try changing the following?

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