Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - How to save javascript variable into Django Database? [duplicate]

Tags:

python

django

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?

like image 373
Parseltongue Avatar asked Nov 19 '25 20:11

Parseltongue


1 Answers

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.

like image 136
mc_kaiser Avatar answered Nov 21 '25 08:11

mc_kaiser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!