You can do that way
from django.db.models import F
def questions(request)
_reponse = Reponse.objects.update(total=F('total') + 1)
return render(request, 'vautmieux/test.html', {'reponse': _reponse})
If you want to add a button to increase the counter so you need to create two separate views one to render the html page and the other to increase the integerfield
So you views.py will look like this
from django.db.models import F
from django.views.decorators.csrf import csrf_exempt
def questions(request)
return render(request, 'vautmieux/test.html', {'reponse': _reponse})
@csrf_exempt
def IncreaseCounter(request):
_reponse = Reponse.objects.update(total=F('total') + 1)
return HttpResponse('the counter has been increased')
and in your url you will have :
path('question_page/', views.questions, name='question-html'),
path('increase_counter/', views.IncreaseCounter, name='Increase-Counter')
And last you need just to add a button to target the second view :
<button onclick="window.location.href='/increase_counter/';"> + 1 </button>
And the ideal way is to use ajax so your page will not refresh every time you click the button, to do so you have to change the onclick function of the button and to add the following script :
<button onclick="increase_counter()"> + 1 </button>
<script type="text/javascript">
$.ajax({
url: '/increase_counter/',
method : 'POST',
success: function(response) {
alert('counter increased')
}
});
</script>
But if you want to use ajax you have to add a csrf_exempt decorator on your view.
In order to update a specific object in your model you need to pass the pk as a variable in your url like so :
path('increase_counter/<int:pk>/', views.IncreaseCounter, name='Increase-Counter')
in your button you will loop change the button to be like this :
<button onclick="window.location.href='/increase_counter/{{ response.pk }}/';"> + 1 </button>
for aajax is the same method you add the pk into the url.
And in your view you will add this :
def IncreaseCounter(request, pk):
_reponse = Reponse.objects.filter(pk=pk).update(total=F('total') + 1)
return HttpResponse('the counter has been increased')