Django表单POST提交后保留并显示用户输入的技术问题
解决Django计算器表单提交后不保留输入值的问题
问题核心在于:表单提交后视图未将填充了用户输入的表单实例传入模板,且验证失败时错误创建了空表单,导致输入值丢失。以下是具体修复方案:
修改views.py
- 表单验证通过时,将已填充数据的
form加入上下文,确保模板能渲染带用户输入的表单 - 验证失败时直接返回当前
form实例(而非新建空表单),保留用户输入与错误提示
from django.shortcuts import render from django.views import View from .forms import InvestmentForm class Index(View): def get(self, request): form = InvestmentForm() return render(request, 'loancalculator/index.html', {'form': form}) def post(self, request): form = InvestmentForm(request.POST) if form.is_valid(): total_result = form.cleaned_data['starting_amount'] total_interest = 0 yearly_results = {} for i in range(1, int(form.cleaned_data['number_of_years'] +1)): yearly_results[i] = {} # 计算利息 interest = total_result * (form.cleaned_data['return_rate'] / 100) total_result += interest total_interest += interest # 追加年度投入 total_result += form.cleaned_data['annual_additional_contribution'] # 记录年度结果 yearly_results[i]['interest'] = round(total_interest, 2) yearly_results[i]['total'] = round(total_result,2) # 上下文添加form实例 context = { 'form': form, 'total_result': round(total_result,2), 'yearly_results': yearly_results, 'number_of_years': int(form.cleaned_data['number_of_years']) } return render(request, 'loancalculator/index.html', context) else: # 验证失败返回原表单,保留用户输入和错误信息 return render(request, 'loancalculator/index.html', {'form': form})
修改index.html
初始加载页面时total_result等结果变量不存在,需添加条件判断避免渲染错误:
{% extends 'loancalculator/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="row justify-content-center"> <div class="col-4 border bg-light"> <div class="row t-5"> <div class="col-12 col-md-6 mx-md-auto"> <h1> Investment Calculator</h1> <h5> Enter the details below to see your estimate</h5> <form action="" method="POST"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-primary" type="submit">Calculate</button> </form> <br> </div> </div> </div> <!-- 仅当存在计算结果时渲染结果区域 --> {% if total_result %} <div class="col-4 border"> <div class="row t-5"> <div class="col-12 col-md-6 mx-md-auto"> <h1>Investment Results</h1> <h3> After {{ number_of_years }} years, your investment is worth ${{ total_result }}</h3> <div class="mt-5"> <table class="table"> <thead> <tr> <th scope="col">Year</th> <th scope="col">Interest</th> <th scope="col">Total</th> </tr> </thead> <tbody> {% for key, value in yearly_results.items %} <tr> <th scope="row">{{ key }}</th> <td>{{ value.interest }}</td> <td>{{ value.total }}</td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> </div> {% endif %} </div> </div> {% endblock content %}
原理说明
- Django表单实例传入
request.POST后会自动保存用户输入,将其传入模板即可在表单中显示历史输入值 - 验证失败返回原表单,既保留用户输入,还能自动展示字段错误提示
- 结果区域添加条件判断,避免初始加载时因变量缺失导致模板渲染异常
内容的提问来源于stack exchange,提问作者jimiclapton
相关产品推荐
相关产品推荐

