[모각코][210728] Vue.js학습3(Django로 TodoApp만들기2)

Jinhyung Rhee·2021년 7월 28일
0
post-thumbnail

(이전 기록과 이어지는 내용임)

Vue.js로 구현했던 기능을 Django로만 구현해보기

  • 1)입력을 받는 form부분 2)저장된 결과를 보여주는 list부분 3)delete기능을 수행하는 부분으로 나누어서 설계
  • 기본적은 html 뼈대는 todo_vue_only.html에서 그대로 가져옴
  • vue가 사용된 부분만 고쳐 django template문법으로 대체
  • < script >태그 없이 설계
  1. templates/todo_form.html 생성
  • form을 그려주는 todo_form.html 작성
  • form을 보여주는 부분만 설계
<!-- 중략 -->
<body>
    <div id = 'app'>
        <h1>My Todo App !</h1>
        <strong>서로 할 일이나 의견을 공유해 봅시다.</strong>
        <br>
        <!-- form을 보여주는 부분만 남겨둠 -->
        <!-- form태그에는 action과 method속성이 필요함 -->
        <form class="inputBox" action="." method="POST"> {% csrf_token %} <!--csrf공격 방지 위한 토큰-->
            <input class="name" type="text" placeholder="name ..." name="name">
            <input class="item" type="text" placeholder="type anyting welcomed ..."
                name="todo"> <!-- 엔터 눌러도 add기능 되도록 구현 -->
            <!-- v-model대신 name속성으로 변경 = 변수명은 todoTable의 변수명과 동일 해야함(주의!) -->
            <button type="submit">ADD</button>
        </form>

    </div>
</body>
</html>
  • form 태그에는 action과 method속성이 필요
  • {% csrf_token %} 을 사용하여 csrf공격 방지
  • v-model 대신 name속성으로 변경
    - 변수명은 todo 테이블 상의 변수명과 동일!
    - "newTodoItem"에서 "todo"로 변경!
  1. templates/todo_list.html 생성
  • 입력된 결과들만 보여주도록 설계
  • form 부분은 지우고 list부분만 남겨둠
<body>
    <div id = 'app'>
        <h1>My Todo App !</h1>
        <strong>서로 할 일이나 의견을 공유해 봅시다.</strong>
        <br>
        <!-- todoList.html에서는 form부분을 지우고 list부분만 만들어줌 -->
        <!-- vue.js코드는 삭제하고 html태그와 장고 템플릿 문법으로 변경-->
        <ul class="todoList">
            <!-- v-for는 장고 템플릿 문법으로 대체 -->
            {% for todo in object_list %} <!-- listView에서는 object_list라는 context 변수를 넘겨줌 -->
            <li>
                <!-- vue.js {mustache문법} -> { { 장고 템플릿 문법 } } 으로 변경 -->
                <span>{{ todo.name }} :: {{ todo.todo }}</span> <!-- column명은 todo임!-->
                <!-- 삭제버튼 클릭했을 때의 동작 <a>태그로 넣어줌 : delete url요청 & 파라미터로 todoID 넣음 -->
                <span class="removeBtn"><a href="{% url 'todo:delete' todo.id %}">&#x00D7</a></span>
            </li>
            {% endfor %}
        </ul>
    </div>
</body>
  • v-for 문법은 장고 템플릿 문법 {% for todo in object_list %}로 대체
    - listView에서는 object_list라는 context변수를 넘겨준다!
  • vue.js의 mustache 문법{}은 장고 템플릿 문법{{ }}으로 대체됨
  • 테이블의 column 명은 todo이므로 'todo.item'에서 'todo.todo'로 변경함
  • 삭제버튼 클릭했을 때의 동작 추가
    - < a >태그를 추가하여 버튼 클릭 시 delete url을 요청하고 파라미터로 'todo.id' 넣어줌!!
  1. templates/todo_confirm_delete.html 생성
  • list.html에서 x표시 눌렀을 때 등장하는 페이지
<body>
    <div id = 'app'>
        <h1>Todo Delete</h1>
        <!-- deleteView에서는 context변수 obejct를 넘겨줌 -->
        <p>Are you sure to delete {{ obeject }} ?</p>
        <br>

        <form action="." method="POST"> {% csrf_token %}
            <button type="submit">Confirm</button>
        </form>
    </div>

</body>
  • DeleteView에서는 object라는 context변수를 넘겨줌!
  1. 이름을 입력하지 않으면 '홍길동'이라는 default값 넣어주는 기능 추가
  • 일반적으로 2가지 방법 사용
    1. form 처리하는 곳에서 구현(todo_form.html)
    2. 데이터베이스 save하는 부분에서 추가(models.py에서 save 메소드 오버라이딩)
    => 두 번째 방법이 일반적인 방법!
# models.py
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
        if not self.name:
            self.name = '홍길동'
        super().save()
  • super().save() : 반드시 상위클래스의 save()메서드를 호출하여 변경된 내용 저장함!
profile
기록하는 습관

0개의 댓글