Sending Lists values in a post request from HTML/JS to bckend(python) [closed]

English is not my first language , so escuse my grammer mistakes 🙂
its my first time workung with JS , i will start by showing the tables in the database and then explain the problem so hopefully any one can help me .
i have these tables :

"# 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)"


each child has a sessions table , and for ech session i can add one or more goals/rating(for each goal).
this is my code which handles the adding/updating a row in session table :

@app.route('/child/<int:child_id>/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))"

i have checked the JS in the output, and it is getting the list correct , but when clicking on update , it removes all the goals besides the first one , and send in the post request only the first goal.
and this is my sessions.html code(i have moved the scripts and css to the page just for the debugging ) :

    <script>
        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 = `
                <textarea class="expandable-textarea" name="${goalsName}"></textarea>
                <select name="${ratingsName}">
                    <option value="" selected disabled>Choose rating</option>
                    ${[...Array(10).keys()].map(i => `<option value="${i+1}">${i+1}</option>`).join('')}
                </select>
                <div class="goal-item-buttons">
                    <button type="button" onclick="removeGoal(this)">Remove</button>
                </div>
            `;
            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);
        }
    </script>
  <style>
        .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;
        }
    </style>
<!DOCTYPE html>
<html>
<head>
    <title>Sessions for {{ child.first_name }} {{ child.surname }}</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='Styles/style.css') }}">
  
</head>
<body>
    <div class="profile-container">
        <h2>Sessions for {{ child.first_name }} {{ child.surname }}</h2>

        <!-- Back Button -->
        <div class="back-button-container">
            <a href="{{ url_for('children_progress') }}" class="btn-back">Back to Children's Progress</a>
        </div>

        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>Therapy Type</th>
                        <th>Session Date</th>
                        <th>Goals</th>
                        <th>Progress Update</th>
                        <th>Activities Performed</th>
                        <th>Notes/Comments</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    {% for session in sessions %}
                    <tr>
                        <form method="post" action="{{ url_for('child_sessions', child_id=child.id) }}">
                            <input type="hidden" name="session_id" value="{{ session.id }}">
                            <td>
                                <select name="therapy_type">
                                    <option value="Therapy 1" {% if session.therapy_type == 'Therapy 1' %}selected{% endif %}>Therapy 1</option>
                                    <option value="Therapy 2" {% if session.therapy_type == 'Therapy 2' %}selected{% endif %}>Therapy 2</option>
                                    <option value="Therapy 3" {% if session.therapy_type == 'Therapy 3' %}selected{% endif %}>Therapy 3</option>
                                    <option value="Therapy 4" {% if session.therapy_type == 'Therapy 4' %}selected{% endif %}>Therapy 4</option>
                                </select>
                            </td>
                            <td><input type="date" name="session_date" value="{{ session.session_date }}"></td>
                            <td>
                                <div class="goal-container">
                                    {% for goal in session.goals %}
                                    <div class="goal-item">
                                        <textarea class="expandable-textarea" name="setting_goals[]">{{ goal.description }}</textarea>
                                        <select name="progress_rating[]">
                                            <option value="" selected disabled>Choose rating</option>
                                            {% for i in range(1, 11) %}
                                            <option value="{{ i }}" {% if goal.rating == i %}selected{% endif %}>{{ i }}</option>
                                            {% endfor %}
                                        </select>
                                        <div class="goal-item-buttons">
                                            <button type="button" onclick="removeGoal(this)">Remove</button>
                                        </div>
                                    </div>
                                    {% endfor %}
                                    <button type="button" class="add-goal-button" onclick="addGoal(this)">Add Goal</button>
                                </div>
                            </td>
                            <td><textarea class="expandable-textarea" name="progress_update">{{ session.progress_update }}</textarea></td>
                            <td><textarea class="expandable-textarea" name="activities_performed">{{ session.activities_performed }}</textarea></td>
                            <td><textarea class="expandable-textarea" name="notes_comments">{{ session.notes_comments }}</textarea></td>
                            <td>
                                <button type="submit" name="update_session">Update</button>
                                <button type="submit" name="delete_session" formmethod="post" style="display:inline;">Delete</button>
                            </td>
                        </form>
                    </tr>
                    {% endfor %}
                    <!-- Form for adding a new session -->
                    <form method="post" action="{{ url_for('child_sessions', child_id=child.id) }}">
                        <td>
                            <select name="therapy_type" required>
                                <option value="Therapy 1">Therapy 1</option>
                                <option value="Therapy 2">Therapy 2</option>
                                <option value="Therapy 3">Therapy 3</option>
                                <option value="Therapy 4">Therapy 4</option>
                            </select>
                        </td>
                        <td><input type="date" name="session_date" required></td>
                        <td>
                            <div class="goal-container">
                                <div class="goal-item">
                                    <textarea class="expandable-textarea" name="setting_goals_new[]" required></textarea>
                                    <select name="progress_rating_new[]" required>
                                        <option value="" selected disabled>Choose rating</option>
                                        {% for i in range(1, 11) %}
                                        <option value="{{ i }}">{{ i }}</option>
                                        {% endfor %}
                                    </select>
                                    <div class="goal-item-buttons">
                                        <button type="button" onclick="removeGoal(this)">Remove</button>
                                    </div>
                                </div>
                                <button type="button" class="add-goal-button" onclick="addGoal(this, 'setting_goals_new[]', 'progress_rating_new[]')">Add Goal</button>
                            </div>
                        </td>
                        <td><textarea class="expandable-textarea" name="progress_update" required></textarea></td>
                        <td><textarea class="expandable-textarea" name="activities_performed"></textarea></td>
                        <td><textarea class="expandable-textarea" name="notes_comments"></textarea></td>
                        <td><button type="submit" name="add_session">Add</button></td>
                    </form>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- Chart Container -->
        <div class="chart-container">
            <canvas id="progressChart"></canvas>
        </div>
    </div>


</body>
</html>
Thanks



I am trying to send two list from html in a post request to backcode , but it only sending the first value in the list and deleting all the others 
logs output after trying to update the the first row after adding "goal2" which it is nor receving at all:

>  DEBUG:root:Full form data: ImmutableMultiDict([('session_id', '46'),
> ('therapy_type', 'Therapy 1'), ('session_date', '2024-07-17'),
> ('setting_goals[]', 'goal 1'), ('progress_rating[]', '5'),
> ('progress_update', 'asd'), ('activities_performed', 'asd'),
> ('notes_comments', 'asd'), ('update_session', '')])
> DEBUG:root:Progress ratings: ['5'] DEBUG:root:Setting goals: ['goal
> 1']  INFO:root:Updating session ID 46 with therapy_type=Therapy 1,
> session_date=2024-07-17, progress_update=asd,
> activities_performed=asd, notes_comments=asd, progress_rating=['5'] 
> INFO:root:Adding goal: goal 1 with rating: 5"

New contributor

ayal khier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

4

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật