2

I have a javascript variable called "counter", which I want to use to update a counter variable instantiated in models.py.

Here is a snapshot of models.py

class Player(BasePlayer):
    #track the number of times the user has lost window focus
    blur_quantity = models.IntegerField(initial=0) 

Here is an example of pages.html

{% block content %}
<button name="blur_button" value=counter onclick="Warn()" class="btn btn-primary btn-large">Blur Button</button>


{% endblock %}
{% block scripts %}
    <script>
        var counter  = 0;
       // Tracks window blurs
       $( document ).ready(function() {
          function onchange (evt) {
            counter++;
            console.log(counter);
          }

          window.onblur = onchange;

        });  

        function Warn() {
            alert(counter);
        }
</script>
{% endblock %}

Now, whenever the user clicks the button, the value of "counter" should be stored somewhere. How do I update the value of blur_quantity in models.py (e.g. my Django database) to reflect the value attached to the blur_button?

Parseltongue
  • 11,157
  • 30
  • 95
  • 160
  • 1
    Along with Ajax, you should take a look at how to integrate CSRF with for security; https://stackoverflow.com/questions/6506897/csrf-token-missing-or-incorrect-while-post-parameter-via-ajax-in-django – markwalker_ Mar 26 '18 at 20:52

2 Answers2

5

JavaScript:

   var counter = 0;

  $( document ).ready(function() {
     function onchange (evt) {
       counter++;
       $.ajax({
         url: '/update_counter/',
         data: {'counter': counter},
         type: 'POST'
       }).done(function(response){
         console.log(response);
       });
     }

     window.onblur = onchange;

   }); 

views.py:

from django.http import HttpResponse
from models import Player

def update_counter(request):
    if request.method == 'POST':
        player = Player.objects.get()
        player.blur_quantity =  request.POST['counter']
        player.save()
        message = 'update successful'
    return HttpResponse(message)

urls.py:

from django.conf.urls import url

from views import update_counter

urlpatterns = [
   url(r'^update_counter/', update_counter)
]

Basically, the ajax in call in the JavaScript sends counter to the server via a POST request. urls.py routes the request to your update_counter method, which updates the database with the value of counter. Finally, the update_counter method returns a response, which is handled by the done function in the JavaScript.

mc_kaiser
  • 717
  • 8
  • 18
  • Thank you so much for your work on this. Should I save urls.py in my root directory? Is that the only line that it should contain? I am using the library otree, which only exposes me to views.py and models.py, so I've never seen urls.py – Parseltongue Mar 26 '18 at 22:39
  • 1
    No problem :) `urls.py` will often go in the same directory as your `models.py` and `views.py`. I've updated answer to reflect what a urls file will often look like. I'm not sure how otree might affect this. I'd suggest having a look at the Django urls docs (https://docs.djangoproject.com/en/1.8/topics/http/urls/) for more info. Note that if you're using Django 2.0 it may look a little different than my example. – mc_kaiser Mar 26 '18 at 23:13
  • Can you please take a look at this :- https://stackoverflow.com/questions/66610832/how-to-save-model-instance-in-django-through-javascript-in-html/66610915#66610915 – Lars Mar 13 '21 at 07:53
1

Inside the onChange method, you can send a POST request to one of your server's endpoint, and let the server updates the database from there. Then the server shall respond back as a response to that POST request with the most updated value of blur_quantity, and use this value as your new counter.

mckuok
  • 744
  • 6
  • 11
  • I know so little about this that it's hard to follow this answer, sorry. I am currently running this all locally, and have two pages models.py and pages.py. What would the post request look like? – Parseltongue Mar 26 '18 at 21:20
  • This can be broken down to client side (js in general) and server side (django for your case). Client: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send You can look at this to learn how to send a POST request Server side: http://www.django-rest-framework.org/tutorial/2-requests-and-responses/ Look for the `request.method == 'POST'` statement and you can update your database from the `request.data`, and return a valid response – mckuok Mar 26 '18 at 21:35
  • Thank you! Will have a go at this – Parseltongue Mar 26 '18 at 21:42