简体   繁体   English

如果django表单提交失败,则运行javascript

[英]running a javascript if a django form submission fails

I have a django app where user can submit a form .I have put this form inside a div (say of id='mydiv_id') which is initially invisible(by css display:none ).When a user want to enter the input ,he clicks a show button on the page ,and a javascript makes the div visible by making display:block . 我有一个django应用程序,用户可以在其中submit a form 。我已将此表单放在div (say of id='mydiv_id') ,该div最初是不可见的(通过css display:none )。当用户想要输入输入时,他点击了页面上的一个show按钮,一个javascript通过display:blockdisplay:block div。

The fields in the form have {{myform.myfield.errors}} so that a ul class="errorlist" will be created if validation fails. 表单中的字段具有{{myform.myfield.errors}}因此如果验证失败,将创建ul class="errorlist"

I want to keep the form visible by running another javascript if the form validation fails.The body of javascript will be just $('#mydiv_id').show(); 如果表单验证失败,我想通过运行另一个javascript来保持表单可见.javascript的主体只是$('#mydiv_id').show();

But how should I make this run? 但是我应该怎么做呢? How do you tell the javascript that django form validation failed without doing the validation inside the javascript? 如果没有在javascript中进行验证,你如何告诉jjjjoo表单验证失败?

I think I need to put the following in javascript body..Other than that I can't figure out how to tell it that form submission failed. 我想我需要在javascript体内添加以下内容。除此之外我无法弄清楚如何告诉它表单提交失败。

$(document).ready(function(){

..
});
def method(request):
    if something_wrong:
        data['error'] = True
    return render_to_response('template.html', data)

and in the template.html you can add the javascript block: 在template.html中,您可以添加javascript块:

{% if error %}
<script type='text/javascript'>
    //the javascript used to show the message
    $(function(){
        $('#mydiv_id').show();
    });
</script>
{%endif%}

if i understand you well 如果我理解你的话

$(document).ready(function(){
    show = {% if form.errors %} true {% else %} false {% endif %}
    if (show) {
       $('#mydiv_id').show();
    }
    else {
    ....
    }

)};

Using javascript to do form validation is a smart thing to do, why make a call to the server if the form is not valid? 使用javascript进行表单验证是一件明智的事情,如果表单无效,为什么要调用服务器呢? You are just making extra overhead to your server by making it do form validation. 您只需通过表单验证就可以为服务器节省额外的开销。 If you do not need to call the server to do form validation there is no reason you should, use javascript to do that. 如果您不需要调用服务器进行表单验证,则没有理由应该使用javascript来执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM