在 Django 中如何比较两个文本并打印有关正确性或错误的消息?

问题描述 投票:0回答:1

我是 Django 新手。在 Django 中,我想比较前端和后端之间的两个文本,并在它们相同或不同时接收消息。实际上,这两个文本是两个简短的 HTML 代码。该页面可以轻松重新加载,我只对比较两个文本背后的逻辑和代码感兴趣(而不是使用 Ajax、jQuery、JS,但如果它不重新加载,显然会更好)。

输入用户。用户将在前端插入文本,黑色

div
无文本区域),其中
contenteditable="true"
已存在于我的代码中。我已经在黑色面板中准备了示例文本,因此我想比较整个 html 文本块(从
<!DOCTYPE html>
</html>
)。由于多种原因,我想使用 div,而不是文本区域。

在后端进行比较的文本。而其他文本将包含在后端(在变量或类似的东西中),并且它将是相同的html代码(考虑到目的是精确比较)。我将要比较的文本插入到名为

corrected_text_backend
的变量中,但我不知道这是否是一个好主意,因为将来我想在比较中添加条件,例如仅比较一小部分代码(而不是整个代码)。所以我想使用更好的方法(如果存在的话)。

比较结果。然后我将单击按钮,在灰色矩形中我想打印

CORRECT: the two texts are the same
ERROR: the two texts are different

重要的是我不想使用textarea,但正如已经说过的,我想使用我的代码中已有的带有contenteditable =“true”的div。

我的逻辑和代码有问题,无法继续处理

views.py
中的代码。你能帮助我并告诉我如何做吗?我是 Django 新手,抱歉。

索引.HTML

{% load static %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>University</title>

    <link rel="stylesheet" href ="{% static 'css/styleparagone.css' %}" type="text/css">

</head>

<body>


  <div class="test">

    <div>Input User</div>
  
      <div class="hilite row">
  
        <pre class="hilite-colors"><code class="language-html"></code></pre>
        <div
             data-lang="html"
             class="hilite-editor"
             contenteditable="true"
             spellcheck="false"
             autocorrect="off"
             autocapitalize="off"
             >&lt;!DOCTYPE html>
&lt;html>
&lt;head>
&lt;title>Page Title&lt;/title>
&lt;/head>
&lt;body>     
             
&lt;h1 class="heading">This is a Heading&lt;/h1>   
&lt;p>This is a paragraph.&lt;/p>
    
&lt;/body>
&lt;/html></div>

  </div>
    
    <div>Comparison Result</div>
    <div class="result row2 rowstyle2"></div>
    
  </div> 

  <form action="{% url 'function_comparison' %}" method="post">
    {% csrf_token %}   
     <button type="submit" name='mybtn'>Button</button>
  </form>

  </div> 

</body>
</html>

CSS

.row {
    width: 500px;
    padding: 10px;
    height: 150px; /* Should be removed. Only for demonstration */
  }
  
  
  .rowstyle1 {
    background-color: black;
    color: white;
  }
  
  .row2 {
    margin-top: 20px;
    width: 500px;
    padding: 10px;
    height: 15px; /* Should be removed. Only for demonstration */
  }
  
  
  .rowstyle2 {
    background-color: #ededed;;
    color: black;
  }
  

MYAPP/URLS.PY

from django.urls import path
from . import views
from . import views as function_comparison

urlpatterns=[
  path('', views.index, name='index'), 
  path('function_comparison/', function_comparison,name="function_comparison"),
]

项目/URLS.PY

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('App1.urls')),
]

我的应用程序/视图.PY

from django.shortcuts import render, redirect
from django.http import HttpResponse

def index(request):
    """View function for home page of site."""
    return render(request, 'index.html')

def function_comparison(request):
    if request.method == "GET":
        corrected_text_backend = """
             <!DOCTYPE html>
             <html>
             <head>
             <title>Page Title</title>
             </head>
             <body>     
         
             <h1 class="heading">This is a Heading</h1>   
             <p>This is a paragraph.</p>

             </body>
             </html>"""

             .....

        return render(request, "index.html")
python html python-3.x django django-views
1个回答
0
投票

好的,这是我认为您的意思的一个有效示例: (有很多东西需要改变,我将在每节中解释)

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>University</title>

    <style>
      .hilite-editor {
        color: white;
        background-color: #2b2b2b;
        width: 500px;
        border: 1px solid #ccc;
        padding: 10px;
        font-family: monospace;
        font-size: 14px;
        line-height: 1.5;
      }

      .row {
        width: 500px;
        padding: 10px;
      }
      
      
      .rowstyle1 {
        background-color: black;
        color: white;
      }
      
      .row2 {
        margin-top: 20px;
        width: 500px;
        padding: 10px;
      }
      
      
      .rowstyle2 {
        background-color: #ededed;;
        color: black;
      }
      
    </style>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
</head>

<body>
<div class="test">

  <div>Input User</div> 
    <div class="hilite row">

      <pre class="hilite-colors"><code class="language-html"></code></pre>
      <div
          id="userinput"
          data-lang="html"
          class="hilite-editor"
          contenteditable="true"
          spellcheck="false"
          autocorrect="off"
          autocapitalize="off"
      >
          &lt;!DOCTYPE html>
      </div>
    </div>
  </div> 
    
  <button type="submit" onclick="getFormData();">Button</button>

  <br><br>
  <div>Comparison Result</div>
  <div class="result row2 rowstyle2" id="result">
    {% comment %} Ajax innerHTML result {% endcomment %}
  </div>
  
</div> 

{% comment %} script to disable "want to send form again" popup {% endcomment %}
<script>
  if ( window.history.replaceState ) {
      window.history.replaceState( null, null, window.location.href );
  }
</script>

<script>
function getFormData() {
    $.ajax({
        type:"GET",
        url: "{% url 'function_comparison' %}",
        data:{
            "formData": document.getElementById("userinput").innerText
        },
        success: function (response) {
            document.getElementById("result").innerHTML = response.message;
        },
        error: function (response) {
            console.log(response)
        }
    });
}
</script>

</body>
</html>

在这里,我使用 AJAX 来处理请求,这使我们能够收集以前表单中的信息(或者在您的情况下,表单仅围绕按钮而不是“输入”字段,但这是一个完整的解释就其本身而言,所以我将跳过该部分)。

我使用 AJAX 的原因是因为您想使用 div 而不是输入字段(文本区域),并且如果您将表单发送到后端,它需要输入字段数据,而我们没有。所以现在它会收集 div 数据并发送该数据,就像您发送表单一样。

我还注意到您的

index.html
表单操作为“POST”,而在
views.py
中您期待的是“GET”。

发送 AJAX 请求至

views.py
后:

from django.http import JsonResponse
from django.shortcuts import render

def index(request):
    return render(request, "index.html")

def function_comparison(request):
    context = {}
    if request.method == "GET":
        corrected_text_backend = """<!DOCTYPE html>"""
        
        user_form_data = request.GET.get("formData", None)

        if user_form_data == corrected_text_backend:
            context["message"] = "Yes, it is the same!"
        else:
            context["message"] = "No, it is not the same!"

    return JsonResponse(context, status=200)

我稍微简化了您的比较文本,以使其更易于阅读,但它的工作原理是一样的。

如您所见,我在这里使用了 JsonResponse,因为我不希望最终用户被重定向(即使是到同一页面)。

就是这样。

结果如下:

尽管这是您所要求的,但如果您的文本中有

\n's
或其他特殊字符,例如
&
%
|
,您可能需要使用正则表达式。

© www.soinside.com 2019 - 2024. All rights reserved.