You need to enable JavaScript to run this app. Django使用CLASS BASED VIEWS实现表单提交后跨页展示计算结果
优惠活动
大模型
产品
解决方案
定价
更多

Django使用CLASS BASED VIEWS实现表单提交后跨页展示计算结果

基于Django类视图实现表单提交-计算-结果展示流程实现方案

第一步:定义表单类

在你的应用forms.py文件中新增表单类,可根据实际计算需求调整字段类型和规则:

# forms.py
from django import forms

class CalculationForm(forms.Form):
    # 示例字段:采集两个用于计算的数字,可按需修改
    num1 = forms.IntegerField(label="第一个数字")
    num2 = forms.IntegerField(label="第二个数字")

第二步:编写两个类视图

# views.py
from django.views.generic import FormView, TemplateView
from django.urls import reverse_lazy
from .forms import CalculationForm

# 视图01:表单提交页
class CalculationFormView(FormView):
    template_name = "form_page.html" # 对应模板01
    form_class = CalculationForm
    success_url = reverse_lazy("calc_result") # 提交成功后跳转至结果页路由

    def form_valid(self, form):
        # 获取表单校验后的清洁数据
        num1 = form.cleaned_data["num1"]
        num2 = form.cleaned_data["num2"]
        # 替换为你的实际数学计算逻辑
        calc_result = num1 + num2
        # 计算结果存入session,方便结果页读取
        self.request.session["calc_result"] = calc_result
        return super().form_valid(form)

# 视图02:结果展示页
class CalculationResultView(TemplateView):
    template_name = "result_page.html" # 对应模板02

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # 从session读取计算结果
        context["result"] = self.request.session.get("calc_result")
        # 可选:读取后清除session,避免重复展示旧结果
        if "calc_result" in self.request.session:
            del self.request.session["calc_result"]
        return context

第三步:配置URL路由

在你的应用urls.py文件中新增路由规则:

# urls.py
from django.urls import path
from .views import CalculationFormView, CalculationResultView

urlpatterns = [
    path("calc-input/", CalculationFormView.as_view(), name="calc_form"),
    path("calc-output/", CalculationResultView.as_view(), name="calc_result"),
]

第四步:编写两个页面模板

模板01:form_page.html(表单采集页)

<!DOCTYPE html>
<html>
<head>
    <title>参数提交</title>
</head>
<body>
    <h3>请输入计算参数</h3>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">提交计算</button>
    </form>
</body>
</html>

模板02:result_page.html(结果展示页)

<!DOCTYPE html>
<html>
<head>
    <title>计算结果</title>
</head>
<body>
    <h3>计算完成</h3>
    <p>最终计算结果为:{{ result }}</p>
    <a href="{% url 'calc_form' %}">返回重新计算</a>
</body>
</html>

可选优化说明

  • 如果计算结果需要持久化存储,可将计算结果写入数据库,跳转时携带结果ID作为URL参数,结果页通过ID查询数据展示即可,无需使用session
  • 表单校验规则、计算逻辑可根据实际业务需求灵活调整,上述代码仅为基础流程演示

内容的提问来源于stack exchange,提问作者Matheus Percário Bruder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 16:54:04