测试.html文件的内容为什么没有显示出来?

huangapple go评论72阅读模式
英文:

Why is the content of the test.html file not showing up?

问题

我正在尝试向我的后端发送许多GET请求,但无法理解发生了什么。

viws.py:

from django.http import HttpResponse
from django.views.generic import TemplateView

class HomePageView(TemplateView):
    template_name = "pages/home.html"

class AboutPageView(TemplateView):
    template_name = "pages/about.html"

class TestPageView(TemplateView):
    template_name = "pages/test.html"
    
    def get(self, request, *args, **kwargs):
        num = request.GET.get('num')
        result = f"test {num} - status: ok"
        return HttpResponse(result)

test.html:

{% extends '_base.html' %}
{% load static %}

{% block title %}Test{% endblock title %}

{% block content %}
<!DOCTYPE html>
<html>

<body>
    <h2>Test server</h2>

    <form id="function_form">
        <button type="submit" id="start_btn">Start</button>
    </form>
    <div id="result"></div>
    <script>
        document.getElementById("function_form").addEventListener("submit", function (event) {
            event.preventDefault();
            for (let i = 1; i <= 1000; i++) {
                fetch('/test/?num=' + i)
                    .then(response => response.text())
                    .then(data => {
                        document.getElementById("result").innerHTML += data + "<br>";
                    });
            }
        });
    </script>
</body>

</html>
{% endblock content %}

urls.py:

from django.urls import path
from .views import HomePageView, AboutPageView, TestPageView

urlpatterns = [
    path("", HomePageView.as_view(), name="home"),
    path("about/", AboutPageView.as_view(), name="about"),
    path("test/", TestPageView.as_view(), name="test"),
]

当我访问/test/或者例如/test/?num=2时,我收到的页面只包含"test 2 - status: ok",与test.html没有任何关联。为什么在/test/上我看不到我预期看到的内容?

英文:

I am trying to send a lot of GET requests to my back-end, but can not understand what happening here

viws.py:

from django.views.generic import TemplateView

class HomePageView(TemplateView):
    template_name = &quot;pages/home.html&quot;

class AboutPageView(TemplateView):
    template_name = &quot;pages/about.html&quot;

class TestPageView(TemplateView):
    template_name = &quot;pages/test.html&quot;
    
    def get(self, request, *args, **kwargs):
        num = request.GET.get(&#39;num&#39;)
        result = f&quot;test {num} - status: ok&quot;
        return HttpResponse(result)

test.html:

{% load static %}

{% block title %}Test{% endblock title %}

{% block content %}
&lt;!DOCTYPE html&gt;
&lt;html&gt;

&lt;body&gt;
    &lt;h2&gt;Test server&lt;/h2&gt;

    &lt;form id=&quot;function_form&quot;&gt;
        &lt;button type=&quot;submit&quot; id=&quot;start_btn&quot;&gt;Start&lt;/button&gt;
    &lt;/form&gt;
    &lt;div id=&quot;result&quot;&gt;&lt;/div&gt;
    &lt;script&gt;
        document.getElementById(&quot;function_form&quot;).addEventListener(&quot;submit&quot;, function (event) {
            event.preventDefault();
            for (let i = 1; i &lt;= 1000; i++) {
                fetch(&#39;/test/?num=&#39; + i)
                    .then(response =&gt; response.text())
                    .then(data =&gt; {
                        document.getElementById(&quot;result&quot;).innerHTML += data + &quot;&lt;br&gt;&quot;;
                    });
            }
        });
    &lt;/script&gt;
&lt;/body&gt;

&lt;/html&gt;
{% endblock content %}

urls.py:

from django.urls import path
from .views import HomePageView, AboutPageView, TestPageView

urlpatterns = [
    path(&quot;&quot;, HomePageView.as_view(), name=&quot;home&quot;),
    path(&quot;about/&quot;, AboutPageView.as_view(), name=&quot;about&quot;),
    path(&quot;test/&quot;, TestPageView.as_view(), name=&quot;test&quot;),
]

After I path to /test/ or, for example, /test/?num=2 I receive a page which has only "test 2 - status: ok" and nothing common with test.html.

Why on /test there is no content that I expected to see?

答案1

得分: 1

问题是你发送一个 HttpResponse 作为对你的 get 请求的答复。

    def get(self, request, *args, **kwargs):
        num = request.GET.get('num')
        result = f"test {num} - status: ok"   # 这里你定义了作为 http 输出看到的字符串
        return HttpResponse(result)  # 这是你发送的纯响应类型

利用 render 函数!

from django.shortcuts import render

class TestPageView(TemplateView):
    template_name = "pages/test.html"

    def get(self, request, *args, **kwargs):
        return render(self.request, self.template_name, context=self.get_context_data())

render 接受参数:第一个是请求,第二个是 模板,第三个是上下文。上下文在类视图的 get_context_data() 方法中定义。你也可以直接传递一个包含你变量的字典。

仔细考虑一下:

实际上,我上面的解决方案是 TemplateView 的默认方式。你只需摆脱“将响应定义为 HttpResponse('一些文本')”,这样就可以正常工作:

class TestPageView(TemplateView):
    template_name = "pages/test.html"

    # 删除整个 get 方法
英文:

The problem is that you send a HttpResponse as answer to your get request.

    def get(self, request, *args, **kwargs):
        num = request.GET.get(&#39;num&#39;)
        result = f&quot;test {num} - status: ok&quot;   # here you define the string that you see as http output
        return HttpResponse(result)  # this is the plain response type that you are sending

Utilize the render function!

from django.shortcuts import render

class TestPageView(TemplateView):
    template_name = &quot;pages/test.html&quot;

    def get(self, request, *args, **kwargs):
        # num = request.GET.get(&#39;num&#39;)
        # result = f&quot;test {num} - status: ok&quot;
        return render(self.request, self.template_name, context=self.get_context_data())

render accepts arguments: First the request, second the template, third the context. Context is defined in the method get_context_data() for class based views. You could also just pass a dictionary there with your variables.

On a second thought:

Actually my solution above is the default of the TemplateView. You just have to get rid of "defining the response as HttpResponse(&quot;some text&quot;)" yourself. So this should work as fine:

class TestPageView(TemplateView):
    template_name = &quot;pages/test.html&quot;

    # delete entire get method

huangapple
  • 本文由 发表于 2023年5月10日 14:14:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76215369.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定