python - Django Exception KeyError 'data' - 只运行一次
问题描述
我正在尝试使用接受来自用户的 2 个输入的 Django 制作一个 Web 应用程序:
- 数学运算符:1 表示加法,2 表示乘法等。
- 页数
基于此,生成并下载数学工作表。所有这些都很好,但只有一次。当我尝试重新生成第二个 PDF 时,出现异常:
- /worksheet/'data' 处的 KeyError
- 请求方法:POST
- 请求网址:http://localhost:8000/worksheet/
- Django 版本:3.2.5 异常
- 类型:KeyError
- 异常值:“数据”异常
- 位置:/Users/rishisaikia/Python
Projects/springdales/spring_env/lib/python3.9/site-packages/fpdf/fpdf.py,第 1515 行,在 _putimages - Python 可执行文件:/Users/rishisaikia/Python
Projects/springdales/spring_env/bin/python - Python版本:3.9.5
- 服务器时间:Sun, 04 Jul 2021 06:49:37 +0000
这是我的文件:
视图.py
from django.shortcuts import render
from . import math_gen
from django.http import FileResponse
def index(request):
return render(request, 'mathwork/index.html')
def worksheet(request):
if request.method =='POST':
practice = request.POST["practice"]
pages = request.POST["pages"]
math_gen.gen_pages(int(practice), int(pages))
math_gen.pdf.output('mathwork/pdf_output/tut.pdf', 'F')
# return render(request, 'mathwork/index.html')
return FileResponse(open('mathwork/pdf_output/tut.pdf', 'rb'), as_attachment=True, content_type='application/pdf')
索引.html
<h1>Welcome to Maths Worksheet Generator</h1>
{% block content %}
<form action="{% url 'mathwork:worksheet' %}" method='POST'>
{% csrf_token %}
<!-- <p>Select Function (1,2,3,4)</p> -->
<input type="text" name='practice'>
<!-- <p>Enter Number of Pages</p> -->
<input type="text" name='pages'>
<button name='submit'>Generate Worksheet</button>
</form>
{% endblock content %}
我究竟做错了什么?
解决方案
我认为“第一次”和其他运行之间的区别在于您生成了 pdf 文件。我可以建议在生成新文件之前尝试删除该文件。
filename = 'mathwork/pdf_output/tut.pdf'
if os.path.isfile(filename):
os.remove(filename)
math_gen.pdf.output(filename, 'F')
推荐阅读
- ruby-on-rails - 如何根据条件验证密码?
- javascript - 如何访问从 MVC 视图中的 ajax 调用调用的控制器返回的数据
- android - Jetpack Compose 中的高度垫片 (HeightSpacer)
- angular - 在 Ionic 4 中使用查询参数
- python - (Maya Python) 如何通过 GUI 函数运行单选选项按钮?
- python - 如何计算 python pandas 数据帧的第一条和最后一条记录之间的时间差异
- azure - Azure 管道“WinRMCustomScriptExtension”基础连接在非公共 VM 中关闭
- python - 在没有附加模块的 lambda 函数中使用反 cos
- vim - 如何在 Vim 中始终将文本保存在缓冲区中>
- excel - 将选项卡组合在一起时设置条件的问题