Rishi
Rishi

Reputation: 97

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:

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?

Upvotes: 0

Views: 67

Answers (1)

Egor Wexler
Egor Wexler

Reputation: 1944

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

Upvotes: 1

Related Questions