【问题标题】:Display message whilst server is running query Django在服务器运行查询 Django 时显示消息
【发布时间】:2011-10-31 06:18:59
【问题描述】:

我有一个很长的任务,一旦客户/用户/客户按下提交按钮就会运行。如何使用 Django 显示一条消息说,等等……查询正在运行,直到查询完成?

【问题讨论】:

  • 为什么不让任务入队呢? (在一个线程中,用芹菜,......)。 (对不起,我知道这不是预期的答案。响应可能类似于:单击“提交按钮”时显示加载消息,收到请求时,新页面覆盖旧页面并删除“加载消息”。一些想法:thecrumb.com/2011/01/21/simple-loading-dialog-wjquery-ui)
  • 提交时使用前端 javascript 显示消息。但这听起来像是一个更大问题的开始,您应该考虑使用异步解决方案

标签: html django


【解决方案1】:

您应该考虑使用 Ajax 来做到这一点。

让我们看一个使用 JQuery 的例子; 如果在您的模板中,您有此表单:

<form id="my_form" action="" method="post">
   <label for="age">Age:</label>
   <input type="text" name="age" id="age"/>
   <input type="submit" value="Submit"/>
</form>
<div id="loading" style="display:none;">Loading...</div>

让我们编写一些 Javascript,假设您已经包含了 Jquery 库:

$(function(){
    $('#my_form').submit(function(event){
       event.preventDefault();

       alert('user submitted the form');
       $('#loading').show();

       $.post('my_url',
              {age : $('#age').val()},
              function(data){
                  $('#loading').hide();
                  alert('server finished to process data.');
              });
    });

});

您可以完全自定义这段代码来做您想做的事。 如果您想在 ajax 中进行更多调试,我建议您按照以下方式声明您的 ajaxSetup:

function ajaxSetup(){

    $.ajaxSetup({
        error:function(x,e){
            if(x.status==0){
                alert('You are offline!!\n Please Check Your Network.');
            }else if(x.status==404){
                alert('Requested URL not found.');
            }else if(x.status==500){
                alert('Internal Server Error.\n' + x.responseText);
            }else if(e=='parsererror'){
                alert('Error.\nParsing JSON Request failed.');
            }else if(e=='timeout'){
                alert('Request Time out.');
            }else {
                alert('Unknow Error.\n'+x.responseText);
            }
        }
    });
}

【讨论】:

  • @Martlark 如果你真的想在 Django 中使用 ajax,查看这个项目dajaxproject.com 可能会有所帮助:)
  • 等我下午睡不着的时候再试试 dajaxproject。
  • 它有点工作,但遇到了包含所有表单数据和跨站点令牌thingo的问题。我还在努力。
【解决方案2】:

这就是我最终使用 JQuery 所做的,并包含一些代码来确定按下了哪个按钮:

<form>
<div id="loading" style="display:none;">Finding all words, may take a long time</div>
<div id="form_input_things">
<input type="submit" name="_save" value="Save" />
<input type="submit" name="_get_words" value="Get Words" />
{{ form.as_p }}
</div>
</form>

<script>
    $("form").submit(function() {
    {
      if( $("[submit_button_pressed=Save]").get(0) === undefined )
      { 
        $('#loading').show();
        $('#form_input_things').hide();
      }
    }
    return true;    
    });

    $(":submit").live('click', function() {
       $(this).attr("submit_button_pressed", $(this).val());
    });
</script>

【讨论】:

  • 这段代码没有回答你最初的问题。顺便说一句,谢谢你不接受我的回答...
  • 它确实回答了我的问题。出现消息,当查询/提交返回带有结果的新页面时显示。它也更易于使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-10
  • 1970-01-01
  • 1970-01-01
  • 2018-04-03
  • 2017-01-21
  • 2020-10-21
  • 2014-07-07
相关资源
最近更新 更多