首页 > 解决方案 > Python 语句在 Django 中无法正常工作

问题描述

我想显示和隐藏 HTML 元素取决于我按下按钮后收到的数据的内容。按下按钮后将创建数据(它是另一个 py 文件的输出),但 if 语句不起作用,{% if data == 'empty' %}它显示的图像不是我想要的按摩。

{% load static %}
<html>
<link rel="stylesheet" type="text/css"
      href="{% static 'css/main.css' %}">
<head>
<title>
Analyze your tweets
</title>
</head>
<br>
<br>    
<h1 class="text-light">Analyze Emotions in Your 2020 Tweets &#128526; </h1>
    
<br>
<br>    
<form action="/external/" method="post">
<div class="outter"  aria-label="actionButtons">
   
<div class="inner">


{% csrf_token %}
<label>Enter your @</label>    
<input id="username" type="text" name="param" placeholder="Username" required >
<input id="btnSearch" type="submit" value="Analyze" onclick="show();">
  </div>
</form>
</div>
 <div class="outter"> 
 <div class="inner">    
<div class="lds-ellipsis" id="load" style="display: none;"><div></div><div></div><div></div></div>
    </div>
    </div>
    
<div class="outter"> 
{% if data %}
    {% if data == 'empty' %}
                   <h5 style="font-family:Lato; color: azure; font-size: 18;">Sorry the username you looking for is either private or doesn't exist </h5>
    {% endif %}
<div class="inner">

          <h5 style="font-family:Lato; color: azure; font-size: 18;">Here is your result <span style="color:black;">@{{data}}</span></h5>
          <img id="pic" src="{% static 'images/graph.png' %}" width="640" height="480" />


 </div>
{% endif %}
</div>
<br>
<br>    
<div class="outter2">     
    <h5>This website will <u>not</u> violate your Account Privacy.</h5>    
<h6> by Reem & Taif</h6>
 </div>   
    
</html>

<script>
    function show(){
        var r = document.getElementById("username");
        if(r == ""){
        var e = document.getElementById("load");
        e.style.display = 'inline-block';
        }
    }
</script>

我尝试添加其他内容但仍然无法正常工作

标签: pythonhtmldjango

解决方案


显示图像是因为它不在您的 if 检查范围内。你应该使用

{% if data == 'empty' %}
    <h5 style="font-family:Lato; color: azure; font-size: 18;">Sorry the username you looking for is either private or does not exist </h5>

{% else %}
    <div class="inner">
    <h5 style="font-family:Lato; color: azure; font-size: 18;">Here is your result <span style="color:black;">@{{data}}</span></h5>
    <img id="pic" src="{% static 'images/graph.png' %}" width="640" height="480" />
    </div>
{% endif %}

我假设您的 python 代码在未提供用户名的情况下显式发送​​字符串“empty”,这将创建一个但如果有人尝试使用值为“empty”的用户名。我将通过检查字符串是否为空来实现相同的目标:

{% if data }
    <!--Add normal data display here-->
{% else %}
    <!--Add empty data display here-->
{% endif %}

就像你之前几乎只做几行一样。


推荐阅读