2016-06-12 32 views
1

我想實現一個投票功能。投票功能無法獲取對象。 vote.js應該沒問題。任何想法?看來POST請求沒有發送。謝謝。投票功能「沒有Eintrag匹配給定的查詢」

這是錯誤:

<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() 
在result.html

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

片斷

urls.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); 
    }) 

}); 

回答

0

看來你有一個請求方法不匹配。你應該在做POST時做一個GET。

此行提出了404,因爲沒有request.POST

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

我邀請你來裝點這個觀點與django.views.decorators.http.require_POST所以你得到的HTTP 405 Method not allowed error,更好地反映超過404

我的方法問題認爲它來自您的Ajax請求如何在JS中完成(請參閱http://api.jquery.com/jquery.ajax/

您可以嘗試更改以下內容嗎?

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

同樣的錯誤:泥說:未找到:/票/ [12月/ 6/2016 18點17分15秒] 「GET /票/ HTTP/1.1」 404 1722 – royaIT

+1

嗯,你總是會如果您執行GET請求時遇到問題,您必須以某種方式將其更改爲POST請求。不要忘記在更改JS文件後收集靜態內容。 – raphv

+0

'code' function.vote(eintragID){$ 阿賈克斯({ 方法: 「POST」, URL: 「/票/」, 數據:{ 「eintrag」:eintragID}, 成功:函數() {「#eintrag-vote-」+ eintragID).hide(); $(「#eintrag-title-」+ eintragID).css({「margin-left」:「15px」}); } , 標題:{ 'X-CSRFToken':csrftoken } }); 返回false; }'code' – royaIT