[Answered ]-Django: create a "changing button" or waiting page

1👍

You’re trying to check a server-side value on the client, but the problem is that the if c.alive statement only gets evaluated when your view is rendered – not as the status of c changes.

You would need to be able to report back the status of c to the client via ajax long polling or WebSockets, or, if you don’t care about the incremental status of c and just want to change the text of the link, you’ll need to use JavaScript to set the value when the click event of the link fires:

// assuming jQuery for brevity...

$(document).ready(function() {

    // avoid hard-coding urls...
    var yourApp = {
        contaUrl: "{% url 'conta' %}"
    };

    $('#btnGo').click(function(e) {
        e.preventDefault();  // prevent the link from navigating

        // set css classes and text of button
        $(this)
            .removeClass('btn-primary')
            .addClass('btn-danger')
            .text('WAIT');

        $.get(yourApp.contaUrl, function(json) {
             window.top = json.redirect;
        });
    });
});

but… your conta function will need to return a JsonResponse instead of an HttpResponse in order to do the redirect on the client-side:

from django.core.urlresolvers import reverse
from django.http import JsonResponse

def conta(request):
    c.prova(0)
    redirect = reverse('name_of_home_user_view')
    return JsonResponse({'redirect': redirect})

1👍

I post my working solution. Thanks to @Brandon for the useful answer.

in conta.js some changes:

$(document).ready(function() {

    // avoid hard-coding urls...
    var yourApp = {
        contaUrl: "/conta/"
    };


    $('#btnGo').click(function(e) {
        e.preventDefault();  
        // set css classes and text of button
        $(this)
            .removeClass('btn-primary')
            .addClass('btn-danger disabled') // with *disabled* I'm sure that the button is not clickable
            .text('WAIT');



        $.get(yourApp.contaUrl, function(json) {     
             alert("I have finished counting");                    
             parent.window.location.reload(true);               


        });
    });
});

in views.py

def conta(request):
    c.prova(0)
    redirect = reverse('home')                  
    return JsonResponse({'redirect': redirect})
👤Trix

Leave a comment