Я впервые работаю с JS, я начну с показа таблиц в базе данных, а затем объясню проблему, так что, надеюсь, кто-нибудь сможет помочь я.
У меня есть эти таблицы:
Код: Выделить всё
"# Children model
class Child(db.Model):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(150), nullable=False)
surname = db.Column(db.String(150), nullable=False)
gender = db.Column(db.String(10), nullable=False)
father_name = db.Column(db.String(150), nullable=True)
mother_name = db.Column(db.String(150), nullable=True)
contact_phone_number = db.Column(db.String(20), nullable=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
Код: Выделить всё
# Session Details model
class SessionDetail(db.Model):
id = db.Column(db.Integer, primary_key=True)
child_id = db.Column(db.Integer, db.ForeignKey('child.id'), nullable=False)
therapy_type = db.Column(db.String(150), nullable=False)
session_date = db.Column(db.String(20), nullable=False)
progress_update = db.Column(db.Text, nullable=True)
activities_performed = db.Column(db.Text, nullable=True)
notes_comments = db.Column(db.Text, nullable=True)
progress_rating = db.Column(db.Integer, nullable=True)
goals = db.relationship('Goal', backref='session', lazy=True)
Код: Выделить всё
# Goal model
class Goal(db.Model):
id = db.Column(db.Integer, primary_key=True)
session_id = db.Column(db.Integer, db.ForeignKey('session_detail.id'), nullable=False)
description = db.Column(db.Text, nullable=False)
rating = db.Column(db.Integer, nullable=False)"
у каждого ребенка есть таблица сеансов, и для каждого сеанса я могу добавить одну или несколько целей/рейтинга (для каждой цели).
"
у каждого ребенка есть таблица сеансов, и для каждого сеанса я могу добавить одну или несколько целей/рейтинга (для каждой цели).
"
у каждого ребенка есть таблица сеансов, и для каждого сеанса я могу добавить одну или несколько целей/рейтинга (для каждой цели).
"
strong>
это мой код, который обрабатывает добавление/обновление строки в таблице сеанса:
Код: Выделить всё
@app.route('/child//sessions', methods=['GET', 'POST'])
def child_sessions(child_id):
child = Child.query.get(child_id)
if not child:
logging.error(f"Child with ID {child_id} not found.")
return 'Child not found', 404
debug_info = None
if request.method == 'POST':
try:
if 'add_session' in request.form:
response = add_session(child_id)
elif 'update_session' in request.form:
response = update_session(request.form['session_id'])
elif 'delete_session' in request.form:
response = delete_session(request.form['session_id'])
else:
response = None
if response:
return response
except Exception as e:
logging.error(f"Error processing session: {e}")
return f"Error: {e}", 500
sessions = SessionDetail.query.filter_by(child_id=child_id).all()
return render_template('sessions.html', child=child, sessions=sessions, debug_info=debug_info)
def add_session(child_id):
try:
logging.debug(f"Full form data: {request.form}")
therapy_type = request.form['therapy_type']
session_date = request.form['session_date']
if not session_date:
raise ValueError("Session date is required.")
progress_update = request.form['progress_update']
activities_performed = request.form.get('activities_performed')
notes_comments = request.form.get('notes_comments')
progress_ratings = request.form.getlist('progress_rating_new[]')
setting_goals = request.form.getlist('setting_goals_new[]')
logging.debug(f"Progress ratings: {progress_ratings}")
logging.debug(f"Setting goals: {setting_goals}")
logging.info(f"Adding session: therapy_type={therapy_type}, session_date={session_date}, "
f"progress_update={progress_update}, activities_performed={activities_performed}, "
f"notes_comments={notes_comments}, progress_rating={progress_ratings}")
new_session = SessionDetail(
child_id=child_id, therapy_type=therapy_type, session_date=session_date,
progress_update=progress_update,
activities_performed=activities_performed, notes_comments=notes_comments,
progress_rating=int(progress_ratings[0]))
db.session.add(new_session)
db.session.flush() # Flush to get the new session ID
for goal, rating in zip(setting_goals, progress_ratings):
logging.info(f"Adding goal: {goal} with rating: {rating}")
new_goal = Goal(session_id=new_session.id, description=goal, rating=int(rating))
db.session.add(new_goal)
db.session.commit()
except KeyError as e:
logging.error(f"Missing form field: {e}")
return f'Error adding session: Missing form field {e}', 400
except ValueError as e:
logging.error(f"Invalid form data: {e}")
return f'Error adding session: {e}', 400
except Exception as e:
logging.error(f"Error adding session: {e}")
return 'Error adding session', 500
return redirect(url_for('child_sessions', child_id=child_id))
def update_session(session_id):
session_detail = SessionDetail.query.get(session_id)
if not session_detail:
logging.error(f"Session with ID {session_id} not found.")
return 'Session not found', 404
try:
logging.debug(f"Full form data: {request.form}")
therapy_type = request.form['therapy_type']
session_date = request.form['session_date']
progress_update = request.form['progress_update']
activities_performed = request.form.get('activities_performed')
notes_comments = request.form.get('notes_comments')
progress_ratings = request.form.getlist('progress_rating[]')
setting_goals = request.form.getlist('setting_goals[]')
session_detail.therapy_type = therapy_type
session_detail.session_date = session_date
session_detail.progress_update = progress_update
session_detail.activities_performed = activities_performed
session_detail.notes_comments = notes_comments
session_detail.progress_rating = int(progress_ratings[0])
Goal.query.filter_by(session_id=session_id).delete() # Delete existing goals for the session
for goal, rating in zip(setting_goals, progress_ratings):
logging.info(f"Adding goal: {goal} with rating: {rating}")
new_goal = Goal(session_id=session_id, description=goal, rating=int(rating))
db.session.add(new_goal)
db.session.commit()
except KeyError as e:
logging.error(f"Missing form field: {e}")
return f'Error updating session: Missing form field {e}', 400
except ValueError as e:
logging.error(f"Invalid form data: {e}")
return f'Error updating session: {e}', 400
except Exception as e:
logging.error(f"Error updating session: {e}")
return 'Error updating session', 500
return redirect(url_for('child_sessions', child_id=session_detail.child_id))"
и это мой код session.html (я переместил скрипты и CSS на страницу только для отладки):
Код: Выделить всё
Sessions for {{ child.first_name }} {{ child.surname }}
.profile-container {
margin: 20px;
}
.table-container {
overflow-x: auto;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: left;
}
.goal-container {
margin-top: 10px;
}
.goal-item {
margin-bottom: 10px;
}
.goal-item-buttons {
margin-top: 5px;
}
.add-goal-button {
margin-top: 10px;
}
.back-button-container {
margin-bottom: 20px;
}
.btn-back {
text-decoration: none;
padding: 10px 20px;
background-color: #007bff;
color: white;
border-radius: 5px;
}
Sessions for {{ child.first_name }} {{ child.surname }}
[url={{ url_for(]Back to Children's Progress[/url]
Therapy Type
Session Date
Goals
Progress Update
Activities Performed
Notes/Comments
Actions
{% for session in sessions %}
Therapy 1
Therapy 2
Therapy 3
Therapy 4
{% for goal in session.goals %}
{{ goal.description }}
Choose rating
{% for i in range(1, 11) %}
{{ i }}
{% endfor %}
Remove
{% endfor %}
Add Goal
{{ session.progress_update }}
{{ session.activities_performed }}
{{ session.notes_comments }}
Update
Delete
{% endfor %}
Therapy 1
Therapy 2
Therapy 3
Therapy 4
Choose rating
{% for i in range(1, 11) %}
{{ i }}
{% endfor %}
Remove
Add Goal
Add
document.addEventListener('DOMContentLoaded', function() {
const formInputs = document.querySelectorAll('.login-form input[type="text"], .login-form input[type="password"], .profile-container form input[type="text"], .profile-container form input[type="tel"], .profile-container form select');
formInputs.forEach(input => {
input.addEventListener('focus', function() {
this.style.borderColor = '#007bff';
});
input.addEventListener('blur', function() {
this.style.borderColor = '#ddd';
});
});
const submitButtons = document.querySelectorAll('.login-form input[type="submit"], .profile-container form button[type="submit"]');
submitButtons.forEach(button => {
button.addEventListener('mousedown', function() {
this.style.backgroundColor = '#004080';
});
button.addEventListener('mouseup', function() {
this.style.backgroundColor = '#007bff';
});
});
});
function addGoal(button, goalsName = 'setting_goals[]', ratingsName = 'progress_rating[]') {
const goalContainer = button.closest('.goal-container');
const newGoalItem = document.createElement('div');
newGoalItem.className = 'goal-item';
newGoalItem.innerHTML = `
Choose rating
${[...Array(10).keys()].map(i => `${i+1}`).join('')}
Remove
`;
console.log(`Adding new goal item with names: ${goalsName}, ${ratingsName}`);
goalContainer.insertBefore(newGoalItem, button);
logFormData(goalContainer);
}
function removeGoal(button) {
const goalItem = button.closest('.goal-item');
console.log('Removing goal item');
goalItem.remove();
const goalContainer = button.closest('.goal-container');
logFormData(goalContainer);
}
function logFormData(goalContainer) {
const goalTexts = goalContainer.querySelectorAll('textarea[name="setting_goals[]"], textarea[name="setting_goals_new[]"]');
const ratingSelects = goalContainer.querySelectorAll('select[name="progress_rating[]"], select[name="progress_rating_new[]"]');
const goals = Array.from(goalTexts).map(textarea => textarea.value.trim()).filter(value => value);
const ratings = Array.from(ratingSelects).map(select => select.value).filter(value => value);
console.log('Current Goals:', goals);
console.log('Current Ratings:', ratings);
}
Я пытаюсь отправить два списка из html в запросе на публикацию в backcode, но он отправляет только первое значение в списке и удаление всех остальных
Подробнее здесь: https://stackoverflow.com/questions/787 ... kendpython