1π
in views.py
def detail(request):
return render(request, 'detail.html', {'posts': Post.objects.all()})
def upvote(request, post_id):
if request.method == "POST":
p = get_object_or_404(Post, pk=post_id)
p.upvote += 1
p.save()
return JsonResponse({'count':p.upvote })
return JsonResponse({})
in detail.html:
{% for post in posts %}
<a href='{% url 'upvote-detail' post.id %}' id='up_voite'>Up voite <span id='voite_count'> {{ post.upvote }} </span> </a>
{% endfor %}
<script>
$(function(){
$('#up_voite').click(function(e) {
e.preventDefault();
$.post($(this).attr('href'), function(data) {
$(this).find('span').html(data.upvote);
});
});
});
</script>
code is not checked
π€comalex3
0π
Try this:
def upvote(request, post_id):
p = get_object_or_404(Post, pk=post_id)
errors = []
data = {}
try:
p.upvote += 1
p.save()
data = {
'success': 1,
}
except:
errors.append(['There was an error'])
data = {
'success': 0,
'errors':errors,
}
return HttpResponse(json.dumps(data))
π€chandu
- Django, ManyToMany, checking the value
- Django-parsley: uncaught error
- Django ORM IF statement
- Django Celery task to continue after error/exception
- Error when returning a HttpResponse from a Django Helper Function
Source:stackexchange.com