-
항해99 4-5일차카테고리 없음 2021. 11. 6. 09:52
오늘 드디어 프로젝트를 제출했다..!
배운거 정리!
1.체크박스 저장해서 불러오기
저번에 제이쿼리 map()을 이용해서 체크된 값을 불러오는 것 까지는 완료
db에 저장은 어렵지 않았움
$.ajax({
type: "POST",
url: "/api/write",
data: {
time1_give: time1,
time2_give: time2,
title_give: title,
content_give: content,
day_give: days//-->days에서 체크된 값을 가져왔기 때문에 에이젝스에서 보내주면 됨
},
success: function (response) {
alert(response["msg"]);
window.location.href = '/'
}
})
}app.py에서는 db에 저장해줘야 하기 때문에 post로 받아와서
다른 값들과 같이 넣어주면 된다
day_receive = request.form.getlist('day_give[]')
를
db.schedule.insert_one(doc)
해주면 됨
그다음..
db에 저장된 값을 수정페이지에서 체크박스 안에 체크되어 있는 상태로 받아줘야 한다.
먼저 배워야 할 것
>파이썬 삼항연산자
{{ "true값" if else "false값" }}
if조건문을 삼항연산자로 쓰면 왼쪽이 if값 가운데가 조건 오른쪽이 else값이 된다.
내가 사용할 조건문: db schedules에 있는 day의 값이 체크가 되어있는 것이면 인풋박스에 체크해줘
{{ "checked" if schedules.day[0] == "true" else "" }}
파이썬 삼항연산자로 if문을 만들어서 체크값이 있으면 인풋에 체크를 해줘야 하는데
1.삼항연산자를 어디에 써줘야하나?
-삼항연산자를 jinja2로
-input값에 찍혀야 하니까 input안에 넣어주기
2.값을 돌면서 체크가 되어있는지를 체크해야 하는데 어떻게 체크할지..
처음에는 {% for schedule in schedules %}로 반복문을 돌려야할 줄 알았다.
<form method="get" action="">
<label><input type="checkbox" name="day"
value="monday" {{ "checked" if schedules.day[0] == "true" else "" }}> 월</label>
<label><input type="checkbox" name="day"
value="tuesday" {{ "checked" if schedules.day[1] == "true" else "" }}> 화</label>
<label><input type="checkbox" name="day"
value="wednesday" {{ "checked" if schedules.day[2] == "true" else "" }}> 수</label>
<label><input type="checkbox" name="day"
value="thursday" {{ "checked" if schedules.day[3] == "true" else "" }}> 목</label>
<label><input type="checkbox" name="day"
value="friday" {{ "checked" if schedules.day[4] == "true" else "" }}> 금</label>
<label><input type="checkbox" name="day"
value="saturday" {{ "checked" if schedules.day[5] == "true" else "" }}> 토</label>
<label><input type="checkbox" name="day"
value="sunday" {{ "checked" if schedules.day[6] == "true" else "" }}> 일</label>
<span class="weekend">
<label><input type="checkbox" name="day"
value="everyweek" {{ "checked" if schedules.day[7] == "true" else "" }}> 매주</label>
</span>
</form>//반복문을 돌게되면 8개의 값을 반복하면서 돌게되니까 적절하지 않음.
하나하나의 값이 체크가 맞는지를 확인해줘야해서 각 인풋 안에 직접 넣어 확인해주었다.
**시간을 선택하는 부분에서도 같은 방법을 사용했는데 좀더 간편한 방법이 없을지**
2.옵션바의 시간을 수정페이지에서 찍어주기
위에서 사용했던 삼항연산자를 이용해서 같은 방법으로 해주었는데
db에 시간이 12:00의 형식으로 저장되어 있어서 : 을 기준으로 시간과 분을 나누었다.
schedules.time.split(':')[0]
<select id="schedule-time1">
<option value="00" {{ "selected" if schedules.time.split(':')[0] == '00' else "" }}>00
</option>
<option value="01" {{ "selected" if schedules.time.split(':')[0] == '01' else "" }}>01
</option>//이런식으로 모든값을 하나하나 돌면서 저장된 값과 같으면 selected해줌
**여기서도 코드를 줄여쓰는 방법이 있는지...?*
3.스케줄작성 페이지와 수정페이지 나누기
스케줄작성 페이지와 수정페이지가 같은 템플릿 안에 있었는데 계속 jinja2오류가 났다.
이렇게 전체 코드를 db의 dchedule값이 있는 것과 없는 것으로 나눠서 작성페이지의 내용에 있는 shedules를 다 지워주었다.
문제-작성 페이지와 수정 페이지가 같은 템플릿을 사용했을때의 문제다.
수정 페이지에서는 기존 데이터를 포함한 뷰를 보여줘야하는데
서버에서 데이터를 템플릿에 넘겨준 후 작성페이지로 접근했을때 데이터가 존재하지 않아 페이지 에러가 발생하였다.
분석-작성과 수정이 데이터를 포함하는지의 여부에 따라 나뉘어 지기 때문에 템플릿이 나뉘여야 할것으로 예상함
해결-jinja2를 사용해서 작성 페이지의 템플릿과 수정페이지의 템플릿을 분기하여 오류를 피할수 있었다.(팀원 분들과 상의한 문제내용)
4.수정페이지 자바스크립트 작성
function edit() {
let params = new URLSearchParams(document.location.search.substring(1))
let u_id = params.get("u_id")
var day = $('input[name="day"]');
var days = $.map(day, function (v) {
return v.checked
}
);
let time1 = $('#schedule-time1').val();
let time2 = $('#schedule-time2').val();
let title = $('#schedule-title').val();
let content = $('#schedule-content').val();
$.ajax({
type: "POST",
url: "/api/edit",
data: {
_id: u_id,
time1_give: time1,
time2_give: time2,
title_give: title,
content_give: content,
day_give: days
},
success: function (response) {
alert(response["msg"]);
window.location.href = '/'
}
})
}수정페이지에서 필요한 자바스크립트 작성 후 버튼에 온클릭을 달아주었다.
route도 하나 더 만들어줌
@app.route('/api/edit', methods=['POST'])
def api_edit():
token_receive = request.cookies.get('mytoken') # 토큰 받아서 디코드
payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256'])
id_receive = payload['id']
_id = request.form['_id']
title_receive = request.form['title_give']
content_receive = request.form['content_give'] # 추가 필요
time1_receive = request.form['time1_give'] # time1 -> hour
time2_receive = request.form['time2_give'] # time2 -> minute
day_receive = request.form.getlist('day_give[]')
doc = {
"id": id_receive,
"subject": title_receive,
"time": time1_receive + ':' + time2_receive, # 시간
"day": day_receive,
"content": content_receive
}db.schedule.update_one({'_id': ObjectId(_id)}, {'$set': doc})//수정페이지니까 업데이트로 작성
return jsonify({'result': 'success', 'msg': '수정되었습니다.'})5.요일에 체크박스가 비어있으면 alert띄워주기
var d = $('input[name="day"]:checked') //input의 name으로 불러오기
console.log(d.length)
if (d.length == 0) {
alert("요일을 체크해주세요.")
return;
}