커뮤니티
포인트
쿠폰
내 강의실
국비 신청 내역
증명서
계정
로그아웃
학습 질문
개발 일지
나의 활동
답변 완료
버튼 클릭 시 데이터 삭제하기
undefined주차
북마크
오*은
댓글
10
추천
0
조회수
257
조회수
257
답변 완료



제목 그대로 버튼 클릭 시 데이터를 삭제하고 싶습니다.

http://sparta-oh.site/ 해당 페이지는 제가 지금까지 만든 페이지입니다.

이 페이지의 첫번째 후기 페이지인 http://sparta-oh.site/reply/[%EB%A6%AC%EB%89%B4%EC%96%BC%20ver.][3M%20%EC%8B%A0%EC%8A%90%EB%A0%88%EC%9D%B4%ED%8A%B8]%EC%98%A4%EB%A6%AC%EC%A7%80%EB%84%90%20M-1965%20%ED%94%BC%EC%89%AC%ED%85%8C%EC%9D%BC%20%ED%8C%8C%EC%B9%B4_Original%20Khaki


에서 밑에 후기 댓글을 삭제하고 싶습니다.


보고 계신 화면 전체를 캡처해 주시면, 튜터님들이 빠르게 상황을 상황을 이해할 수 있어요.

스파르타 즉문즉답




후기 작성 시 POST를 통해 num을 저장해서 해당 num을 찾아와 데이터를 삭제하고 싶은데

num을 넣으면 DB에 "" 라고만 뜨고 저장이 안되네요 어디서 부터 코드를 수정해야 될까요?


reply.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <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>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat&display=swap" rel="stylesheet">
    <link href="{{ url_for('static', filename='css/reply.css') }}" rel="stylesheet" type="text/css"/>
    <link rel="icon" type="image/png" href="{{ url_for('static', filename='images/musinsa.png') }}">
    <title>무신사 실시간 랭킹</title>
    <script src="https://kit.fontawesome.com/fa9d346fc7.js" crossorigin="anonymous"></script>
    <script>
        let comment = '{{ comment }}'
        $(document).ready(function () {
            show_comment_info();
            show_comment('asc');
            show_image();
        });

        function save_comment() {
            let comment = '{{ comment }}'
            let num = '{{ num }}'
            console.log(num, comment)
            let name = $('#name').val()
            let reply = $('#reply').val()
            console.log(`/reply/post/${reply}`)
            $.ajax({
                type: 'POST',
                url: `/reply/post`,
                data: {num_give: num, name_give: name, reply_give: reply, comment_give: comment},
                success: function (response) {
                    alert(response['msg'])
                    window.location.reload()
                }
            })
        }

        function show_comment_info() {

            console.log(comment)
            $.ajax({
                type: 'POST',
                url: `/reply/show`,
                data: {comment_give: comment},
                success: function (response) {
                }
            })
        }


        function show_image() {
            $.ajax({
                type: "GET",
                url: `/musinsa`,
                data: {},
                success: function (response) {
                    let rows = response['musinsas']
                    for (let i = 0; i < rows.length; i++) {
                        let comments = rows[i]['comment']
                        let image = rows[i]['image']
                        let temp_html = `<div class="form-floating mb-4">
                                            <img src="${image}" alt="">
                                        </div>`
                        if(comment === comments){
                            $('.mb-4:nth-child(1)').append(temp_html)
                        }
                    }
                }
            });
        }

        function show_comment(props) {
            const orderValue = props; // 정렬기준
            $('#comment-list').empty()
            $.ajax({
                type: "GET",
                url: `/reply/show?comment_give=${comment}`,
                data: {},
                success: function (response) {
                    let rows = response['replys']
                    if (orderValue === 'asc') {
                        for (let i = 0; i < rows.length; i++) {
                            let name = rows[i]['name']
                            let reply = rows[i]['reply']
                            let comment = rows[i]['comment']
                            let temp_html = `<div class="card-body">
                                                <blockquote class="blockquote mb-0">
                                                    <p>${reply}</p>
                                                    <footer class="blockquote-footer">${name}</footer>
                                                    <button onclick="delete_post(${comment})" type="button" class="btn btn-danger">X</button>
                                                </blockquote>
                                            </div>`

                            $('#comment-list').append(temp_html)
                        }

                    } else if (orderValue === 'desc') {
                        for (let i = rows.length - 1; i > 0; i--) {
                            let name = rows[i]['name']
                            let reply = rows[i]['reply']
                            let comment = rows[i]['comment']
                            let temp_html = `<div class="card-body">
                                                <blockquote class="blockquote mb-0">
                                                    <p>${reply}</p>
                                                    <footer class="blockquote-footer">${name}</footer>
                                                    <button onclick="delete_post(${comment})" type="button" class="btn btn-danger">X</button>
                                                </blockquote>
                                            </div>`
                            $('#comment-list').append(temp_html)
                        }
                    }
                }
            });
        }

        function delete_comment(num) {
            $.ajax({
                type: "POST",
                url: `/reply/delete`,
                data: {num_give: num},
                success: function (response) {
                    alert(response["msg"])
                    window.location.reload()
                }
            });
        }

        const recnetly = (props) => {
            const value = props;
            show_comment(props);
        }
        $(document).ready(function () {
            let weatherIcon = {
                '01': 'fas fa-sun',
                '02': 'fas fa-clouds-sun',
                '03': 'fas fa-cloud',
                '04': 'fas fa-cloud-meatball',
                '09': 'fas fa-cloud-sun-rain',
                '10': 'fas fa-cloud-showers-heavy',
                '11': 'fas fa-poo-storm',
                '13': 'fas fa-snowflake',
                '50': 'fas fa-smog'
            };

            $.ajax({
                url: 'http://api.openweathermap.org/data/2.5/weather?q=Seoul&appid=bc93a7cbed56048a9a9214bd29ef4b25&units=metric',
                dataType: 'json',
                type: 'GET',
                success: function (data) {
                    var $Icon = (data.weather[0].icon).substr(0, 2);
                    var $Temp = Math.floor(data.main.temp) + '°';

                    $('.CurrIcon').append('<i class="' + weatherIcon[$Icon] + '"></i>');
                    $('.CurrTemp').prepend($Temp);
                }
            })
        });

    </script>
</head>
<body>
<div class="nav-bar">
    <div class="nav-wrap">
        <h2><a href="/">MUSINSA</a></h2>
        <div class="weather">
            <div class="CurrIcon"></div>
            <div class="CurrTemp"></div>
        </div>
    </div>
</div>
<div class="mypost">
    <div class="form-floating mb-4">
        <img src="" alt="">
    </div>
    <div class="form-floating mb-4">
        <input type="text" class="form-control" id="name" placeholder="name">
        <label for="floatingInput">이름</label>
    </div>
    <div class="form-floating">
                <textarea class="form-control" placeholder="Leave a comment here" id="reply"
                          style="height: 100px"></textarea>
        <label for="floatingTextarea2">후기</label>
    </div>
    <button onclick="save_comment()" type="button" class="btn btn-dark">후기 남기기</button>
</div>
<div class="mycards">
    <div>
        <select onchange="recnetly(this.value)">
            <option value="asc">최신순▽</option>
            <option value="desc">최신순△</option>
        </select>
    </div>
    <div id="comment-list"></div>
</div>
</body>
</html>


app.py


from flask import Flask, render_template, request, jsonify

app = Flask(__name__)
import requests
from bs4 import BeautifulSoup
from pymongo import MongoClient
import certifi

ca = certifi.where()

client = MongoClient('mongodb+srv://test:sparta@cluster0.rfofzeu.mongodb.net/Cluster0?retryWrites=true&w=majority',
                     tlsCAFile=ca)
db = client.dbsparta
url = 'https://www.musinsa.com/ranking/best'

response = requests.get(url)

if response.status_code == 200:
    html = response.text
    soup = BeautifulSoup(html, 'html.parser')
    ul = soup.select_one('#goodsRankList')
    titles = ul.select('p.item_title > a')
    rank = ul.select_one('p.txt_num_rank').text[0:20].strip()
    image = ul.select('div.list_img > a > img')
    comment = ul.select('p.list_info > a')
    price = ul.select('div.article_info > p.price')
    sex = ul.select('div.icon_group > ul > li')
    url = ul.select('div.list_img > a')

    # for i, title in enumerate(titles):
    #     print(str(i + 1) + f"위", title.text, image[i]["data-original"], comment[i]["title"],
    #           price[i].text[10:38].strip().replace("\n", "").replace(" ", ""), sex[i]['title'], url[i]['href'])

    for i, title in enumerate(titles):
        titles[i] = title.text.strip()
        title = titles[i]
        rank = str(i + 1)
        musinsa_list = list(db.musinsa.find({}, {'_id': False}))
        count = len(musinsa_list) + 1
        doc = {
            'num': count,
            'dune': 0,
            'rank': rank,
            'title': title,
            'image': image[i]["data-original"],
            'comment': comment[i]["title"].replace("/", ""),
            'price': price[i].text[10:38].strip().replace("\n", "").replace(" ", ""),
            'sex': sex[i]["title"],
            'url': url[i]['href']
        }
        # print(rank, title, image[i]["data-original"], comment[i]["title"], price[i].text[10:38].strip(), sex[i]['title'])
        # db.musinsa.insert_one(doc)
else:
    print(response.status_code)


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


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


@app.route("/musinsa", methods=["GET"])
def musinsa_get():
    musinsa_list = list(db.musinsa.find({}, {'_id': False}))
    print(musinsa_list)
    return jsonify({'musinsas': musinsa_list})


@app.route('/reply/<comment>')
def reply(comment):
    print(comment)
    return render_template("reply.html", comment=comment)


@app.route('/reply/post', methods=["POST"])
def reply_post():
    num_receive = request.form.get('num_give')
    name_receive = request.form['name_give']
    reply_receive = request.form['reply_give']
    comment_receive = request.form['comment_give']
    print(name_receive, reply_receive, comment_receive)
    doc = {
        'num': num_receive,
        'comment': comment_receive,
        'name': name_receive,
        'reply': reply_receive
    }

    db.reply.insert_one(doc)

    return jsonify({'msg': '후기 작성 완료!'})


@app.route("/reply/show", methods=["POST", "GET"])
def show_comment():
    comment_receive = request.args.get('comment_give')
    print(comment_receive)
    comment_list = list(db.reply.find({'comment': comment_receive}, {'_id': False}))
    print(comment_list)
    return jsonify({'replys': comment_list})


@app.route('/reply/delete', methods=['POST'])
def delete_post():
    comment_receive = request.form['comment_give']
    db.reply.delete_one({'comment': comment_receive})
    return jsonify({'msg': '삭제 완료'})


@app.route("/musinsa/done", methods=["POST"])
def musinsa_done():
    num_receive = request.form['num_give']
    db.musinsa.update_one({'num': int(num_receive)}, {'$set': {'dune': 1}})
    return jsonify({'msg': '찜하기 완료!'})


@app.route('/musinsa/delete', methods=['POST'])
def delete_star():
    num_receive = request.form['num_give']
    db.musinsa.update_one({'num': int(num_receive)}, {'$set': {'dune': 0}})
    return jsonify({'msg': '찜하기 취소!'})


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

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