Django: create a “changing button” or waiting page

前端 未结 2 905
野性不改
野性不改 2020-12-10 23:31

I have an external python program, named c.py, which \"counts\" up to 20 seconds. I call it from my Django app views.py and in the html page I have a butto

2条回答
  •  忘掉有多难
    2020-12-11 00:08

    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})
    

提交回复
热议问题