如何根据返回的错误控制模板渲染? Django

问题描述:

我想在用户提交表单后显示加载GIF,但如果用户未填写必填字段并收到表单填写错误,则不显示。如何根据返回的错误控制模板渲染? Django

这是我做过什么:

{% if not profile_form.errors %} 

    <input type="submit" value="Submit" class="btn btn-primary btn-lg " onclick="loading();" /> 
{% else %} 
    <input type="submit" value="Submit" class="btn btn-primary btn-lg" /> 

{% endif %} 

onclick="loading();负载GIF。

但它不起作用。

它显示加载gif,如果我提交也如果用户没有填写必填字段,这看起来表单被绞死。

这是函数:

function loading(){ 
    $("#loading").show(); 
    $("#content").hide();  
} 

这是模板:

{% block body_block %} 
<div id="loading"><img src= "{% static 'images/giphy.gif' %}"></div> 

<div id="content" class="col-sm-6 col-sm-offset-3" style="margin-top: 100px;margin-bottom: 100px" > 

<h1>Create Your Profile</h1> 

    <form method="post" action="?next=/" enctype="multipart/form-data"> 
       {% csrf_token %}      
       {{ user_form|crispy }} 
       {{ profile_form|crispy }} 

{% if not profile_form.errors %} 

    <input type="submit" value="Submit" class="btn btn-primary btn-lg " onclick="loading();" /> 
{% else %} 
    <input type="submit" value="Submit" class="btn btn-primary btn-lg" /> 

{% endif %} 
     </form>  

</div> 
{% endblock %} 

这是CSS:

/*LOADING GIF*/ 
div#loading { 
    display: none; 
    cursor: wait; 
    position: fixed; 
    top: 50%; 
    left: 50%; 
    transform: translate(-50%, -50%); 
    z-index: 4; 
    } 
+1

*但它不起作用。*展开。由于视图中的第一个渲染没有错误,因此至少会显示GIF,直到窗体在视图中得到验证。你可以改为使用JS验证。 –

+1

发布功能代码?你在哪里宣布你的功能? – Exprator

+0

我添加了一个编辑。 – Seio

你误解了逻辑流在这里。直到之后表单提交后,视图才重新呈现模板以显示这些错误。在首先提交表单的时候,永远不会有任何错误,所以你的if语句总是如此。

由于Raja在评论中说,唯一的方法是通过Ajax提交表单,然后通过JS显示gif。

+0

大概时间你在这里!节省了我们的时间! :) –

+1

我不得不偶尔睡觉。有时我甚至做一些工作...... –