커뮤니티
포인트
쿠폰
내 강의실
국비 신청 내역
증명서
계정
로그아웃
학습 질문
개발 일지
나의 활동
답변 완료
4주차 숙제 문제가 생겨 도움 요청 드립니다.
undefined주차
북마크
최*수
댓글
4
추천
0
조회수
10
조회수
10
답변 완료


4주차 숙제 작성후 실행하고 이름 응원 댓글 작성후 응원 남기기 하면 파이참에서 에러가 발생 하며 아무런 변화가 없습니다.

제가 작성 한 코드와 전혀 차이를 인식할수 없구요

예제의 index 를 통째로 복사해 붙여넣고 실행하면 댓글 작성후 응원남기기 버튼을 누르면 파이몽고에는 저장되지만 페이지에는 표시가 되질 않구요



스파르타 즉문즉답




작성한 코드 및 에러 메세지

app.py

from flask import Flask, render_template, request, jsonify
app = Flask(__name__)

from pymongo import MongoClient
client = MongoClient('mongodb+srv://test:sparta@cluster0.xsppcfn.mongodb.net/cluster0?retryWrites=true&w=majority')
db = client.dbsparta

@app.route('/')
def home():
   return render_template('index.html')

@app.route("/homework", methods=["POST"])
def homework_post():
    name_receive = request.form['name_give']
    comment_receive = request.form['comment_give']

    doc = {
        'name':name_receive,
        'comment':comment_receive
    }
    db.homework.insert_one(doc)

    return jsonify({'msg':'응원 완료!'})

@app.route("/homework", methods=["GET"])
def homework_get():
    comment_list = list(db.homework.find({}, {'_id': False}))
    return jsonify({'comment':comment_list})

if __name__ == '__main__':
   app.run('0.0.0.0', port=5000, debug=True)


index.html

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
        crossorigin="anonymous"></script>

    <title>팬명록 제작(완전체)</title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+KR:wght@200;300;400;500;600;700;900&display=swap" rel="stylesheet">
    <style>
        .mytitle {
            width: 100%;
            height: 300px;

            background-image: linear-gradient(0deg, rgba(0, 0, 0, 2), rgba(0, 0, 0, 0.2)), url('https://img.sbs.co.kr/newsnet/etv/upload/2022/09/19/30000790950_1280.jpg');
            background-position: center 20%;
            background-size: cover ;

            color: white;

            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            }
        .mypost {
            width: 95%;
            max-width: 500px;
            margin: 20px auto 0px auto;
            padding: 20px;
            box-shadow: 0px 0px 3px 0px gray;
        }
        .mypost > .button {
            margin-top: 20px;
        }
        .mycards {
            margin: auto;
            width: 95%;
            max-width: 500px;
        }
        .mycards > .card {
            margin-top: 10px;
            margin-bottom: 10px;
        }
    </style>
    <script>
         $(document).ready(function(){
            set_temp()
            show_comment()
        });
       function set_temp(){
            $.ajax({
                type: "GET",
                url: "http://spartacodingclub.shop/sparta_api/weather/ulsan",
                data: {},
                success: function (response) {
                    let temp = response['temp']
                    $("#temp").append(temp)
                }
            })
        }

        function save_comment(){
            let  name = $('#name').val()
            let  comment = $('#comment').val()
           $.ajax({
                type: 'POST',
                url: '/homework',
                data: {name_give: name, comment_give: comment },
                success: function (response) {
                    alert(response['msg'])
                    window.location.reload()

                }
            })
        }
        function show_comment(){

           $.ajax({
                type: "GET",
                url: "/homework",
                data: {},
                success: function (response) {
                   let rows = response['comment']
                    for (let i = 0; i < rows.length; i++) {
                        let name = rows[i]['name']
                        let comment = rows[i]['comment']

                        let temp = `<div class="card-body">
                                        <blockquote class="blockquote mb-0">
                                            <p>${comment}</p>
                                            <footer class="blockquote-footer">${name}</footer>
                                        </blockquote>
                                    </div>`
                        $('#comment-list').append(temp)

                    }
                }
            })
        }

    </script>
</head>

<body>
<div class="mytitle">
    <h1>아이유 팬명록</h1>
    <p>현재 기온 : <span id="temp"></span>도</p>
</div>
<div class="mypost">
    <div class="form-floating mb-3">
        <input type="email" class="form-control" id="floatingInput" placeholder="name@example.com">
        <label for="floatingInput">닉네임</label>
    </div>
    <div class="form-floating">
            <textarea class="form-control" placeholder="Leave a comment here" id="floatingTextarea2"
                      style="height: 100px"></textarea>
        <label for="floatingTextarea2">응원댓글</label>
    </div>
    <div class="button">
        <button onclick="save_comment()" type="button" class="btn btn-dark">응원 남기기</button>
    </div>
</div>
<div class="mycards" id="comment-list">
    <div class="card">
        <div class="card-body">
            <blockquote class="blockquote mb-0">
                <p>어른인줄 알았는데 아직도 아이유?</p>
                <footer class="blockquote-footer">김원숭 소장</footer>
            </blockquote>
        </div>
        <div class="card-body">
            <blockquote class="blockquote mb-0">
                <p>맙소사...</p>
                <footer class="blockquote-footer">뜨거운 타조</footer>
            </blockquote>
        </div>
        <div class="card-body">
            <blockquote class="blockquote mb-0">
                <p>됴아~</p>
                <footer class="blockquote-footer">대포동 이정음</footer>
            </blockquote>
        </div>
    </div>
</div>
</body>

</html>


취소
 공유
취소
댓글 0
댓글 알림
나의얼굴