首页 > 解决方案 > 如何打印从 Django 中的表单获得的值?

问题描述

我正在尝试创建一个表单,要求用户输入一个值,对其进行一些计算并将结果显示给用户。这是我所做的:我创建了一个名为 QMarcum 的应用程序。在这个应用程序中,我有这个 views.py、forms.py 和 urls.py:

视图.py

from django.shortcuts import render
from scipy.integrate import quad
import scipy, numpy, math
from scipy import integrate
from django.http import HttpResponse
from .forms import Calculate

def integrand(x):
    Q_y = (1/(math.sqrt(2*math.pi)))*math.exp((-x**2)/2)
    return Q_y
    y = Calculate.y
    ans, err = quad(integrand, float(y), math.inf)
    print(ans)
    return render(request, 'test.html', {'form': Q_y})

表格.py

from django import forms

class Calculate(forms.Form):
    y = forms.FloatField()

网址.py

from django.urls import path
from . import views

urlpatterns = [
    path('form', views.integrand),
]

表单.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form method="post">
        {% csrf_token %}
        {{ form }}
        <button type="submit">Submit</button>
    </form>
</body>
</html>

该表单要求用户输入一个值(y)(y在终端上成功打印),但是,print(ans)不打印该值,而且我也不知道如何向ans用户显示计算结果()。

提前致谢。

标签: pythondjangodjango-modelsdjango-formsdjango-views

解决方案


您的实施中有几个问题。

首先,任何视图的第一个参数始终是request。这些对象让您可以访问与用户浏览器发出的请求有关的许多不同变量。

在这种情况下,您希望使用从用户接收到的数据“填充”您的表单,但您还希望显示页面以便用户看到表单。

如果用户正在访问该页面,您要做的是返回 html,如果用户已提交表单,则接受该信息。

为此,您需要分离不同 HTTP 方法之间的逻辑:

  • GET 返回 HTML
  • POST 接受信息
from django.http import HttpResponse
from .forms import Calculate

def integrand(request):
    if request.method == 'POST':       # accept the information
        form = Calculate(request.POST) # "populate" a form with that data
        print(form.data["y"])          # print the value of y
        # add additional logic with the data here
        return HttpResponse("Thank you for submitting!")
    else: # show the form to the user
        return render(request, 'test.html', {'form': Calculate()})

推荐阅读