编辑市长对问题和文字进行了更改以明确说明。事实证明,错误是由一个非常愚蠢的错误引起的,我忘了将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>
最后是观点。我添加了一些print语句来确定它失败的地方。感谢@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?')
任何帮助解决问题都将受到高度赞赏!如果问题仍然不明确,我会尽量澄清或添加尽可能多的信息!
答案 0 :(得分:0)
尝试:
response_dict = "{'success' : 'true', 'voted_as': '%s'}" % (delta)
您的代码中的%运算符后面有一个无关的s。它应该是% (delta)
此外,您应该会发现您可以在浏览器开发人员工具中查看Django的信息性错误页面(请查看“网络”部分),假设您已设置DEBUG = True。格式化可能已关闭,但它仍然可以帮助您更快地解决代码错误。
编辑:OP固定错字详述如下:
如果这不是您问题中的拼写错误:except Vote.DoesNotExists:
except Vote.DoesNotExist: