好的,这就是我所做的。
在新的voting.html 中,我有这段代码来捕获操纵杆映射到的箭头按钮:
<div id="Vote" class = "high">
<div style="text-align: center">
{% for entry in voting_entry_list %}
<li><a href="/entries/{{ entry.id }}/">{{ entry.text }} {{ entry.score }}</a></li>
<p>
<input type="submit" id="voteid" name='voteid' value="{{ entry.id }}" autofocus value="" onfocus="this.value = this.value;" class = "transparent"/>
<script>
$(document).ready(function() {
$("#voteid").bind("keydown", function(e) { //input type=id above
if (e.keyCode == 38) {
var text = $("#voteid").val();
var args = {'voteid':text};
$.get("/voteup/", args).done(function(data) {
console.log("message: " + data);
location.reload();
});
return false;
}
if (e.keyCode == 40) {
var text = $("#voteid").val();
var args = {'voteid':text};
$.get("/votedown/", args).done(function(data) {
console.log("message: " + data);
location.reload();
});
return false;
}
});
});
</script>
{% endfor %}
</div>
</div>
然后在 views.py 中,我使用 GET 而不是 POST 来捕获赞成票或反对票:
def voting(request):
context = {
'latest_entry_list': Entry.objects.order_by('-pub_date')[:10], # simple sorting by datetime, latest first, 10 items
'high_entry_list': Entry.objects.order_by('-score','-pub_date')[:10], # simple sorting by score high to low, 10 items
'high_entry': Entry.objects.order_by('-score','-pub_date')[:1], # simple sorting by score high to low, 10 items
'low_entry_list': Entry.objects.order_by('score','-pub_date')[:10], # simple sorting by score low to high, 10 items
'voting_entry_list': Entry.objects.unvoted_or_random(), # actually one item, command from extended object manager
}
return render(request, 'entries/voting.html', context); # returns when vote is accessed
def voteup(request):
voting_id = request.GET.get('voteid') # voting id number is brought in as var
if request.method=='GET': #always polling, when get votes, save and redirect to /index to refresh
v = Entry.objects.get(pk=voting_id) # get by voting id var
v.score +=1 # add one to score for voteup button
v.voted=True # set voted boolean to true
v.save() # explicit save, as is not saved with change above
else:
pass
return HttpResponse('done') # Only on console
def votedown(request):
voting_id = request.GET.get('voteid') # voting id number is brought in as var
if request.method=='GET': #always polling, when get votes, save and redirect to /index to refresh
v = Entry.objects.get(pk=voting_id) # get by voting id var
v.score -=1 # add one to score for voteup button
v.voted=True # set voted boolean to true
v.save() # explicit save, as is not saved with change above
else:
pass
return HttpResponse('done') # Only on console
这似乎避免了表单和按键的任何问题。由于它在一个单独的投票页面上,透明的虚拟提交按钮使该选择在刷新时处于活动状态,而不是当它们在同一页面上时的文本输入框。我可以从voting_entry_list 中访问已排序的条目,并使用单独的js 脚本和views.py 请求对每个按钮进行投票。
我的目标是使用基本的 django 和 js 来完成这项工作,对安装大量库或编写额外的 gamepad.api 状态和轮询没有信心,所以工作完成了!
目前这只是一种组合,但看起来很稳固。将来,我可能会尝试通过按键开关来简化它,如果这是一个安全问题,我可能会尝试使用 POST 而不是 GET。