admin管理员组文章数量:1278820
I'm developing a Flask-based school hub app where teachers can create exams. However, I'm encountering an issue where class_id
is "undefined"
when submitting the form.
Issue:
When I submit the form, Flask logs the following:
DEBUG - Raw Form Data: {'title': '1', 'class_id': 'undefined', 'description': '1'}
ERROR - Validation failed: Invalid or missing class_id
Even though class_id
exists in my form and is being set dynamically from the backend (Jinja) or fetched via JavaScript, it still appears as "undefined"
in Flask's request.form
.
Flask Route (create_exam
)
@main.route('/create_exam', methods=['POST'])
@login_required
def create_exam():
if current_user.role != 'teacher':
return jsonify({'error': 'Unauthorized'}), 403
logger.debug(f"Raw Form Data: {dict(request.form)}")
title = request.form.get('title')
class_id = request.form.get('class_id')
description = request.form.get('description')
logger.debug(f"Received Exam Data - Title: {title}, Class ID: {class_id}, Description: {description}")
if not class_id or class_id.strip().lower() in ["undefined", "null", "none", ""]:
logger.error(f"Validation failed: Invalid or missing class_id. Received: {class_id}")
return jsonify({'error': 'A valid class ID is required'}), 400
try:
class_id = int(class_id)
except ValueError:
return jsonify({'error': 'Class ID must be a valid number'}), 400
class_entry = Class.query.get(class_id)
if not class_entry:
return jsonify({'error': 'Invalid class or unauthorized access'}), 403
try:
exam = Exam(title=title, class_id=class_id, description=description, teacher_id=current_user.id)
db.session.add(exam)
db.sessionmit()
return jsonify({'message': 'Exam created successfully'}), 201
except Exception as e:
db.session.rollback()
return jsonify({'error': 'Failed to create exam'}), 500
HTML Form
<form id="exam-form" action="/create_exam" method="POST">
<div class="mb-3">
<label for="title" class="form-label">Exam Title</label>
<input type="text" class="form-control" id="title" name="title" required>
</div>
<div class="mb-3">
<label for="class_id" class="form-label">Select Class</label>
<select class="form-control" id="class_id" name="class_id" required>
{% if class_codes %}
<option value="" disabled selected>Select a class</option>
{% for class_code in class_codes %}
<option value="{{ class_code.id }}">{{ class_code.code }}</option>
{% endfor %}
{% else %}
<option disabled>No class codes available</option>
{% endif %}
</select>
</div>
<button type="submit" class="btn btn-primary">Create Exam</button>
</form>
JavaScript (Fetching Class Codes & Debugging Submission)
document.addEventListener("DOMContentLoaded", function () {
const classSelect = document.getElementById("class_id");
fetch("/get_class_codes")
.then(response => response.json())
.then(data => {
console.log("[DEBUG] Received class codes:", data);
if (classSelect.options.length <= 1) {
classSelect.innerHTML = ""; // Clear only if Jinja hasn't preloaded
let defaultOption = document.createElement("option");
defaultOption.value = "";
defaultOption.disabled = true;
defaultOption.selected = true;
defaultOption.textContent = "Select a class";
classSelect.appendChild(defaultOption);
data.forEach(classCode => {
let option = document.createElement("option");
option.value = classCode.id;
option.textContent = classCode.code;
classSelect.appendChild(option);
});
}
})
.catch(error => console.error("[DEBUG] Error fetching class codes:", error));
});
// Debugging Form Submission
document.getElementById("exam-form").addEventListener("submit", function (event) {
let classSelect = document.getElementById("class_id");
console.log("[DEBUG] Selected class ID:", classSelect.value);
if (!classSelect.value || classSelect.value === "undefined") {
event.preventDefault();
alert("Please select a valid class.");
}
});
- Checked
document.getElementById("class_id").value
before submitting → It logs the correct class ID. - Checked Flask
request.form
output → It logs"undefined"
. - Manually selected an option before submitting → Still logs
"undefined"
. - Used
fetch("/get_class_codes")
to populate the dropdown → The options are generated correctly, but still,"undefined"
is sent.
What I Expected:
- The selected
class_id
should be sent properly and received by Flask as a valid integer. request.form.get("class_id")
should return the selected class ID instead of"undefined"
.
Questions:
- Why is
class_id
being sent as"undefined"
? - Could the issue be caused by JavaScript interfering with form submission?
- Is there a better way to debug form data in Flask?
本文标签: javascriptFlask Form Submission classid is quotundefinedquot When Creating an ExamStack Overflow
版权声明:本文标题:javascript - Flask Form Submission: class_id is "undefined" When Creating an Exam - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741245478a2364789.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论