首页 > 解决方案 > Django Exception KeyError 'data' - 只运行一次

问题描述

我正在尝试使用接受来自用户的 2 个输入的 Django 制作一个 Web 应用程序:

  1. 数学运算符:1 表示加法,2 表示乘法等。
  2. 页数

基于此,生成并下载数学工作表。所有这些都很好,但只有一次。当我尝试重新生成第二个 PDF 时,出现异常:

这是我的文件:

视图.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 %}

我究竟做错了什么?

标签: pythondjango

解决方案


我认为“第一次”和其他运行之间的区别在于您生成了 pdf 文件。我可以建议在生成新文件之前尝试删除该文件。

filename = 'mathwork/pdf_output/tut.pdf'
if os.path.isfile(filename):
    os.remove(filename)

math_gen.pdf.output(filename, 'F')

推荐阅读