I've developed a streamlined system for entering and displaying short texts on a single web page. The text input is a simple input field with a GET in views. To enhance user interaction, I'm looking to implement a basic up or down voting system for the most recent entries. Some individuals online have suggested passing a variable to JavaScript as a first step.
Without utilizing forms or POST yet, as they seem excessive for my requirements, I'm seeking guidance on how to transfer my variable to JS effectively.
Below are snippets of code;
template
<script type="text/javascript">
{% for entry in voting_entry %}
var votingEntry="{{entry.id}}"
{% endfor %}
</script>
<script type="text/javascript" src="{{STATIC_URL}}vote.js"></script>
vote.js
$(document).ready(function() {
$("#votingEntry").bind("keypress", function(e) {
if (e.keyCode == 38) {
var vote = $("#votingEntry").val();
var args = {'vote':vote};
$.get("/vote/", args).done(function(data) {
location.reload();
});
}
});
views
def index(request):
context = {
'latest_entry_list': Entry.objects.order_by('-pub_date')[:10],
'high_entry_list': Entry.objects.order_by('-score')[:10],
'low_entry_list': Entry.objects.order_by('score')[:10],
'voting_entry': Entry.objects.order_by('-pub_date')[:1],
}
return render(request, 'entries/index.html', context);
*snip*
def vote(request):
voting_id = request.GET.get('vote')
v = Entry.objects.get(pk='voting_id')
v.score +=1
v.save()
return HttpResponse('votedone')