I am using python and flask, and I am trying to make a web application for making flashcards. However, when I try to submit my flashcards (i.e., when I fill out the fields “course”, “lecture”, “front” and “back”, and press “Enter”), I get the error “Unsupported Media Type Did not attempt to load JSON data because the request Content-Type was not ‘application/json’.”. To my understanding, I am executing my JSON properly, but there seems to be a mistake somewhere. Can anyone help me or give recommendations? Any help is appreciated. This is my app.py.
from flask import Flask, request, render_template, redirect, flash, jsonify, make_response
import sqlite3
import random
app = Flask(__name__)
# Set a secret key for the session cookie
app.secret_key = "secret"
# Connect to the database
conn = sqlite3.connect("flashcards.db")
db = conn.cursor()
# Create a table to store the flashcards
db.execute("CREATE TABLE IF NOT EXISTS flashcards (id INTEGER PRIMARY KEY, user TEXT, course TEXT, lecture INTEGER, front TEXT, back TEXT)")
conn.commit()
@app.route("/", methods=["GET", "POST"])
def make():
if request.method == "GET":
user = request.cookies.get("user")
if user:
# Get the courses and lectures from the database using the db variable
db.execute("SELECT DISTINCT course FROM flashcards WHERE user = ?", (user,))
courses = db.fetchall()
db.execute("SELECT DISTINCT lecture FROM flashcards WHERE user = ?", (user,))
lectures = db.fetchall()
# Pass the courses and lectures to the render_template function
return render_template("make.html", courses=courses, lectures=lectures)
else:
# If there are no cookies, generate a random user name
user = "user" + str(random.randint(1000, 9999))
# Pass the user name to the render_template function
return render_template("make.html", user=user)
elif request.method == "POST":
# Get the JSON data from the request
data = request.get_json()
# Get the user, course, lecture, front, and back values
user = data["user"]
course = data["course"]
lecture = data["lecture"]
front = data["front"]
back = data["back"]
# Check if the course already exists in the database, and if not, create a new one using the db variable
db.execute("INSERT INTO courses (name) SELECT ? WHERE NOT EXISTS (SELECT 1 FROM courses WHERE name = ?)", (course, course))
conn.commit()
# Check if the lecture already exists in the database, and if not, create a new one using the db variable
db.execute("INSERT INTO lectures (course, number) SELECT ?, ? WHERE NOT EXISTS (SELECT 1 FROM lectures WHERE course = ? AND number = ?)", (course, lecture, course, lecture))
conn.commit()
# Add the flashcard using the db variable
db.execute("INSERT INTO flashcards (user, course, lecture, front, back) VALUES (?, ?, ?, ?, ?)", (user, course, lecture, front, back))
conn.commit()
# Create a response object
response = make_response(jsonify({"success": True}))
# Set a cookie with the user value
response.set_cookie("user", user)
# Return the response object
return response
And this is my “make.html”
{% extends "layout.html" %}
{% block title %}
Make
{% endblock %}
{% block main %}
<h1>Make Flashcards</h1>
<div class="container">
<div class="row">
<div class="col-md-6">
<form id="flashcard-form" method="POST" action="/">
<div class="form-group">
<label for="course">Course</label>
<input type="text" class="form-control" id="course" name="course" placeholder="Enter the course name" list="courselist" required>
<datalist id="courselist">
{% for course in courses %}
<option value="{{ course }}">{{ course }}</option>
{% endfor %}
</datalist>
</div>
<div class="form-group">
<label for="lecture">Lecture</label>
<input type="number" class="form-control" id="lecture" name="lecture" placeholder="Enter the lecture number" list="lecturelist" required>
<datalist id="lecturelist">
{% for lecture in lectures %}
<option value="{{ lecture }}">{{ lecture }}</option>
{% endfor %}
</datalist>
</div>
<div class="form-group">
<label for="front">Front</label>
<input type="text" class="form-control" id="front" name="front" placeholder="Enter the question or term" required>
</div>
<div class="form-group">
<label for="back">Back</label>
<input type="text" class="form-control" id="back" name="back" placeholder="Enter the answer or definition" required>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
{% endblock %}
<script>
// Adding an event listener to the form which triggers when the user presses the enter key
document.getElementById("flashcard-form").addEventListener("keydown", function(event) {
// Checking if the key being pressed is "Enter"
if (event.keyCode === 13) {
// Preventing the default form submission
event.preventDefault();
// Getting the front and back input values
var front = document.getElementById("front").value;
var back = document.getElementById("back").value;
// Creating a data object to send to the server
var data = {front: front, back: back};
// Using fetch to send the data to the server
fetch("/", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(function(response) {
// Handling the response from the server
return response.json();
})
.then(function(data) {
// If the data was successfully sent, show a message and clear the fields
if (data.success) {
alert("Flashcard created successfully!");
document.getElementById("front").value = "";
document.getElementById("back").value = "";
} else {
// If the submission failed, show an error message
alert("Flashcard creation failed!");
}
})
.catch(function(error) {
// Handle any errors
console.error(error);
});
}
});
</script>
I tried checking my imports, and they seem all fine. I also tried asking Copilot and ChatGPT, but they also say that my code looks fine. For some reason, I seem to have issues when using the debugger of VScode.