I am trying to make a web app using Django that accepts 2 inputs from the user:
- Mathematical Operator: 1 for addition, 2 for multiplication, etc.
- Number of Pages
Based on this, a math worksheet is generated and downloaded. All of this works out fine, but only once. When I try to regenerate a second PDF, I get an exception:
- KeyError at /worksheet/ ‘data’
- Request Method: POST
- Request URL: http://localhost:8000/worksheet/
- Django Version: 3.2.5 Exception
- Type: KeyError
- Exception Value: ‘data’ Exception
- Location: /Users/rishisaikia/Python
Projects/springdales/spring_env/lib/python3.9/site-packages/fpdf/fpdf.py, line 1515, in _putimages - Python Executable: /Users/rishisaikia/Python
Projects/springdales/spring_env/bin/python - Python Version: 3.9.5
- Server time: Sun, 04 Jul 2021 06:49:37 +0000
Here are my files:
views.py
JavaScript
x
17
17
1
from django.shortcuts import render
2
from . import math_gen
3
from django.http import FileResponse
4
5
6
def index(request):
7
return render(request, 'mathwork/index.html')
8
9
def worksheet(request):
10
if request.method =='POST':
11
practice = request.POST["practice"]
12
pages = request.POST["pages"]
13
math_gen.gen_pages(int(practice), int(pages))
14
math_gen.pdf.output('mathwork/pdf_output/tut.pdf', 'F')
15
# return render(request, 'mathwork/index.html')
16
return FileResponse(open('mathwork/pdf_output/tut.pdf', 'rb'), as_attachment=True, content_type='application/pdf')
17
index.html
JavaScript
1
13
13
1
<h1>Welcome to Maths Worksheet Generator</h1>
2
3
{% block content %}
4
<form action="{% url 'mathwork:worksheet' %}" method='POST'>
5
{% csrf_token %}
6
<!-- <p>Select Function (1,2,3,4)</p> -->
7
<input type="text" name='practice'>
8
<!-- <p>Enter Number of Pages</p> -->
9
<input type="text" name='pages'>
10
<button name='submit'>Generate Worksheet</button>
11
</form>
12
13
{% endblock content %}
What am I doing wrong?
Advertisement
Answer
I think the difference between ‘first’ and other runs is that you have your pdf file generated. I can suggest to try to remove the file before generating a new one.
JavaScript
1
6
1
filename = 'mathwork/pdf_output/tut.pdf'
2
if os.path.isfile(filename):
3
os.remove(filename)
4
5
math_gen.pdf.output(filename, 'F')
6