You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中实现表单提交后将字段传递至URL并展示清洗后的数据?

解决方案

咱们分步骤搞定你要的两个需求:让URL带上job_number,同时在新页面展示清洗后的数据。

1. 调整URL配置,支持带job_number的路径

首先更新urls.py,把quote/的路径改成能捕获job_number参数的形式,这样提交后的URL就会变成http://127.0.0.1:8000/quote/你的job_number值/:

urlpatterns = [
    path('home/', quote_view, name='home'),
    # 这里用<str:job_number>捕获URL中的参数,要是你的job_number是数字类型,改成<int:job_number>就行
    path('quote/<str:job_number>/', submitted_quote, name='quote'),
]

2. 修改表单提交后的重定向逻辑

在quote_view里,表单验证通过并保存后,我们要拿到清洗后的job_number,然后重定向到带该参数的新页面。直接从保存后的实例里取job_number会更稳妥(毕竟已经存入数据库了):

@login_required
def quote_view(request):
    data_form = QuoteInformationForm()
    if request.method == "POST":
        data_form = QuoteInformationForm(request.POST)
        if data_form.is_valid():
            # 保存表单并获取数据库实例
            quote_instance = data_form.save(commit=True)
            # 重定向到带job_number的quote页面
            return redirect('quote', job_number=quote_instance.job_number)
        else:
            # 建议打印错误信息,方便调试表单验证失败的问题
            print('表单验证失败:', data_form.errors)
    return render(request, "index.html", {'data_form': data_form})

3. 改造submitted_quote视图,获取并传递清洗后的数据

现在submitted_quote需要接收job_number参数,然后根据这个参数从数据库里取出对应的记录,把清洗后的数据传给模板展示。如果不想查数据库,也可以把清洗后的数据存在session里,但从数据库查询更可靠:

from .models import QuoteInformation  # 记得导入你的模型类

@login_required
def submitted_quote(request, job_number):
    try:
        # 根据job_number查询对应的记录
        quote_record = QuoteInformation.objects.get(job_number=job_number)
        # 构建清洗后的数据结构,把你需要展示的字段都加进来
        cleaned_data = {
            'job_number': quote_record.job_number,
            # 示例:添加其他字段,比如quote_record.customer_name、quote_record.quote_amount等
        }
    except QuoteInformation.DoesNotExist:
        # 处理找不到记录的情况,返回404页面
        return HttpResponseNotFound("对应的报价记录不存在")
    
    # 把清洗后的数据传递给模板
    return render(request, "quote.html", {'cleaned_data': cleaned_data})

4. 在quote.html模板中展示数据

最后在模板里用Django的模板语法渲染数据就行:

<h2>提交成功!</h2>
<div class="quote-details">
    <p>Job Number:{{ cleaned_data.job_number }}</p>
    <!-- 这里添加其他你需要展示的字段,比如{{ cleaned_data.customer_name }} -->
</div>

额外小提示

  • 如果你的job_number是数字类型,记得把URL里的<str:job_number>改成<int:job_number>,视图里的参数类型也要对应。
  • 要是不想从数据库查询,也可以在quote_view里把data_form.cleaned_data存入session,然后在submitted_quote里取出,但要注意session的存储限制。

内容的提问来源于stack exchange,提问作者mfrwll

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 05:57:32