Skip to content
Advertisement

Django Exception KeyError ‘data’ – Only runs once

I am trying to make a web app using Django that accepts 2 inputs from the user:

  1. Mathematical Operator: 1 for addition, 2 for multiplication, etc.
  2. 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

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')

index.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 %}

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.

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

math_gen.pdf.output(filename, 'F')
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement