编辑市长对问题和文本进行了更改以使其清楚。事实证明,该错误是由一个非常愚蠢的错误引起的,即我忘记将 HttpResponse 导入到我的 views.py 中。由于在同一个views.py中我处理了另一个视图,我假设它是导入的。菜鸟失误。:(
问题: 我正在尝试通过 ajax 提交赞成票或反对票。显然,我认为大多数代码都已执行,然后在返回响应时失败。问题是django没有显示错误;我在终端中获得的唯一信息是:“POST /c/vote/ HTTP/1.1”500 10814。其中 /c/vote/ 是应该处理投票的 URL。
Chrome 中的控制台也没有多大帮助。我得到的错误是“加载资源失败:服务器响应状态为 500(内部服务器错误)”,然后如果我单击链接,我将被重定向到 /c/vote/,其中 django 返回 404。注意我我在不同的网址投票(即/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?')
任何解决问题的帮助将不胜感激!如果问题仍然不清楚,我将尝试澄清或添加尽可能多的信息!