I have a working django voting system using up and down keypresses on entries in a database.
I need to have the {{ entry.score }} refresh on the page without a reload, as there will be other entries on the page. The {{ entry.text }} can refresh but needs to stay as the same entry until a different keypress selects a different entry.
I'm trying to do it with ajax, but get a 500 Internal Server Error and no refresh,
GET http://127.0.0.1:8000/voteup/?voteid=30 500 (INTERNAL SERVER ERROR) jquery.min.js:4
send jquery.min.js:4
n.extend.ajax jquery.min.js:4
n.(anonymous function) jquery.min.js:4
(anonymous function) (index):76
n.event.dispatch jquery.min.js:3
r.handle
even though the vote goes through correctly...
(index):76 in voting.html is: $.get("/voteup/", args).done(function(data) {
voting.html
<div class = "table">
<div id="Vote" class = "vote">
<div style="text-align: left">
{% 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>
var data = '#Vote';
var url = "/voting/";
$(document).ready(function() {
$("#voteid").bind("keydown", function(e) { //input #submit?????
if (e.keyCode == 38) {
var text = $("#voteid").val();
var args = {'voteid':text};
$.get("/voteup/", args).done(function(data) {
console.log("message: " + data);
$.ajax({
url: url,
data: data,
dataType: 'html',
success: function(data){
$(this).html(data); //this?
}
});
});
return false;
}
});
});
</script>
{% endfor %}
</div>
</div>
</div>
views.py
def index(request):
context = { # actually one item, command from extended object manager
'voting_entry_list': Entry.objects.unvoted_or_random(),
}
return render(request, 'entries/index.html', context);
def voting(request):
context = {'voting_entry_list': Entry.objects.random(),}
return render(request, 'entries/voting.html', context);
def voteup(request):
voting_id = request.GET.get('voteid')
e = Entry.objects.unvoted_or_random()
context = {'voting_entry_list': e,}
if request.method=='GET':
v = Entry.objects.get(pk=voting_id)
v.score +=1
v.voted=True
v.save()
context = {'voting_entry_list': v,}
else:
pass
return render(request, 'entries/voting.html', context);
Models.py
class EntryManager(models.Manager): #a basic extention to the model basemanager to insert new sorting
def unvoted_or_random(self): # command definition uses models input
unvoted_entries = self.filter(voted = False).order_by('-pub_date') # sorted by youngest unvoted entries from any user
voted_entries = self.filter(voted = True).order_by('?') # if no unvoted entries, voted boolean enables random selection '?'
if unvoted_entries: # for boolean unvoted
return unvoted_entries[:1] # return latest
else: # for boolean voted
return voted_entries[:1] # return random