I am very new to Flask, SQL and Html integration. This is done for the fun of learning something new only. I am self taught so my code is def beginner level. I have searched similar posts, but after spending days on this i now need some help.
I have a project utilising SQLlite, FLask and Html. I am wanting to pull through data from SQL - which i can do, then either display it in another page, open within the same page, show further information based on the selection etc as required..
However, the issue is that I cannot get(utilise, print out on screen etc) the selected person from a drop down list - no matter what i try.
I can pull through a drop down list which retrieves a list of users from my students table and is shown in html. (see below)
my database has a table called students. 2 of the fields are username, surname I can access sqlite fine and pull through query without an issue.
some of my code from app.py
def Teachers_ht():
if request.method == "POST":
# Handles my form submission
return submit()
else:
# shows the page with student names again
return students_list()
def students_list():
try:
# Retrieve all student names from the database
student_names = Students.query.with_entities(Students.firstname, Students.surname).all()
if not student_names:
error_message = "No students found in the database."
return render_template('500.html', error_message=error_message), 500
print(student_names) # Should print the student names to the console for debugging - cannot see anything
return render_template('teachers.html', student_names=student_names)
except Exception as e:
error_message = str(e) # Get the error message and shows in my 500.html below
return render_template('500.html', error_message=error_message), 500
def submit():
selected_student_id = request.form.get('student_id')
selected_student = None # placeholder, to ensure variable esits (i think)
if selected_student_id:
# Retrieve the selected student from the database
selected_student = Students.query.get(selected_student_id)
# Retrieve all students' first names and surnames from the database
student_names = Students.query.with_entities(Students.firstname, Students.surname).all()
return render_template('teachers.html', student_names=student_names, selected_student=selected_student)
my html: teachers.html
<div id="selected_student_id">
{% if selected_student_id %}
<h2>Selected Student ID:</h2>
<p>{{ selected_student_id }}</p>
{% endif %}
</div>
<script>
document.getElementById('submit_button').addEventListener('click', function() {
var form = document.getElementById('student_form');
var formData = new FormData(form);
// Sends a POST request to the /submit endpoint
fetch('/submit', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
// Updates the selected student's details section
var selectedStudentDetails = document.getElementById('selected_student_details');
selectedStudentDetails.innerHTML = ''; // Clear existing content
if (data.selected_student) {
var h2 = document.createElement('h2');
h2.textContent = 'Selected Student Details:';
selectedStudentDetails.appendChild(h2);
var p = document.createElement('p');
p.textContent = data.selected_student.firstname + ' ' + data.selected_student.surname;
selectedStudentDetails.appendChild(p);
}
})
.catch(error => {
console.error('Error:', error);
});
});
</script>
Hopefully the above is enough, thankyou for looking.
My website does not error, but neither does it do show any output. I have gone through tutorials and this website. I have confirmed that i can get and post data within other htmls using a submit box, type in a name and i can retrieve this to the same webpage.
Resolved
I have now resolved this, essentially in the html it now reads
<div>
{{form.student_i(size=1)}} ```
in the forms i have a new class
```class TeachersForm(FlaskForm):
submit = SubmitField('Enter')
student_i = SelectField(u'student_i')
def __init__(self, *args, **kwargs):
super(TeachersForm, self).__init__(*args, **kwargs)
students = Students.query.all()
choices = [("", "Select a student")] # Empty option
# here the student id is hidden from the user, but the firstname and surname are shown
choices += [(student.studentid, f"{student.firstname} {student.surname}") for student in students]
self.student_i.choices = choices