EDIT 시장이 변경되어 질문과 텍스트가 명확 해졌습니다. 그것이 오류로 밝혀지면 HttpResponse를 내 views.py로 가져 오는 것을 잊어 버린 매우 어리석은 실수로 오류가 발생합니다. 동일한 views.py에서 다른 뷰를 처리하므로 가져온 것으로 가정했습니다. 신기한 실수. :(HttpResponse에서 AJAX 호출에 500 오류가 발생할 수있는 이유는 무엇입니까?
질문 :.. I가 제출하거나 아약스를 통해 투표를 아래로 시도하고있어 실패 응답을 반환 한 후 때 분명히 내보기에 대부분의 코드가 실행될 때, 문제가 더이 있다는 것입니다 없습니다 장고에 의해 표시되는 오류, 내가 터미널에서 얻을 수있는 유일한 정보는 "POST/c/vote/HTTP/1.1"500 10814입니다./c/vote /는 투표를 처리해야하는 URL입니다
콘솔 Chrome에서 많은 도움이되지 않습니다. 오류는 "리소스를로드하지 못했습니다 : 서버가 500 (내부 서버 오류) 상태로 응답했습니다."링크를 클릭하면/c/vote로 리디렉션됩니다./django가 404를 반환하는 곳. 참고 나는 다른 URL (예 : /c/<country>/
)
투표가 실제로 저장되거나 삭제되어 응답을 반환 할 때 문제가 발생할 수 있다는 것을 알았습니다.
내 템플릿 (사용자가 이전에 투표 한 경우 사용자 정의 템플릿 태그가 알고) :
<div class="vote_buttons" x:id="{{linkpost.pk}}">
<a href="#" class="upVote{% if linkpost|is_up_voted_by:user %} voted{%endif%}" x:value="1" ></a>
<a href="#" class="downVote{% if linkpost|is_down_voted_by:user %} voted{%endif%}" x:value="-1"></a>
JS 코드 (내가 jQuery를 사용하고 있습니다). {{vote_url}} 변수는 템플릿 태그와 함께 전달됩니다. :
<script type="text/javascript">
$(document).ready(function() {
$(".vote_buttons").bind("vote", function(event, value) {
var vote_el = $(this);
$.ajax({
type:'POST',
url: '{{ vote_url }}',
data: {
'pk': vote_el.attr("x:id"),
'delta': value
},
dataType: "json",
success : function(data, textStatus, jqXHR) {
switch (data.voted_as) {
case 1:
vote_el.find("a.upVote").addClass("voted");
vote_el.find("a.downVote").removeClass("voted");
break;
case -1:
vote_el.find("a.upVote").removeClass("voted");
vote_el.find("a.downVote").addClass("voted");
break;
}
},
});
});
$('.upVote, .downVote').click(function(){
$(this).parent().trigger("vote", $(this).attr("x:value"));
return false;
});
});
</script>
그리고 마지막으로보기. 어디에서 실패하는지 알아 내기 위해 몇 가지 인쇄 문을 추가했습니다. @Steven 덕분에 코드는 12 단계까지 계속 실행됩니다. 그러면 앞서 언급 한 오류가 발생합니다.
def vote(request):
"""
Likes or dislikes a linkpost.
"""
print "Setp 1 ok!"
#User must be authenticated to vote.
if request.is_ajax():
print "Step 2 ok"
if request.method == 'POST' and request.user.is_authenticated():
print "Step 3 ok"
delta = request.POST['delta']
# In case an error occurrs with delta value
try:
delta = int(delta)
print "Step 4 ok"
except ValueError:
print "Error was value error"
return HttpResponse("{'success': 'false'}")
# You can only vote upwards or downwards
if not delta in (1, -1):
print "Error was in delta"
return HttpResponse("{'success': 'false'}")
print "Step 5 ok"
#We check if the linkpost actually exists!
LinkPost = get_model('company', 'LinkPost')
try:
linkpost = LinkPost.objects.get(pk=request.POST['pk'])
print "Step 6 ok"
except LinkPost.DoesNotExist:
print "Link object does not exist"
return HttpResponse("{'success': 'false'}")
#We check if the user voted before.
Vote = get_model('company', 'Vote')
try:
vote = Vote.objects.get(linkpost = linkpost, listener = request.user)
print "Step 7 ok!"
except Vote.DoesNotExist:
print "Vote doesn't exists!"
vote = None
# If there is already a vote
if vote:
print "Step 8."
if vote.delta == delta:
vote.delete()
else:
print "Step 9."
vote.delta = delta
vote.save()
#There wasn't a vote, we create one.
else:
print "Step 10."
Vote.objects.create(linkpost = linkpost,
listener = request.user,
delta = request.POST['delta'])
response_dict = {'success' : 'true', 'voted_as': delta}
print "Step 12."
return HttpResponse(simplejson.dumps(response_dict), mimetype="application/json")
else:
print "User not authenticated"
raise Http404('What are you doing here?')
else:
print "Request isn't ajax"
raise Http404('What are you doing here?')
문제를 찾는 데 도움이 될만한 도움이 필요하십니까? 질문이 아직 불분명하다면 가능한 한 많은 정보를 명확히하거나 추가하려고 노력할 것입니다!
은 무엇입니까 :와
except Vote.DoesNotExists:
다음 더 많은 행운을 가질 수는 오류? –
어디서'{{vote_url}} '변수를 템플릿에 전달했는지 알 수 없습니다. 귀하의 아약스 요청이 올바르게 처리됩니까? –
안녕하세요, 죄송합니다.나는 이것에 아주 새롭고 오류를 추적 할 방법을 찾지 못했습니다. 내 질문을 수정하여 오류를 표시하고 vote_url을 템플릿에 전달하는 방법을 보여줍니다. –