230906_postgreSQL_4_2

장종민·2023년 9월 6일

mentor

목록 보기
22/24

html에 띄우기

  • index.html생성

    • <!-- index.html -->
      <!DOCTYPE html>
      <html>
        <head>
          <title>Item List</title>
        </head>
        <body>
          <h1>Item List</h1>
          <ul>
            {% for item in items %}
            <li>
              ID: {{ item.id }}, Name: {{ item.name }}, Description: {{
              item.description }}
            </li>
            {% endfor %}
          </ul>
        </body>
      </html>
      
  • views.py수정

    • from rest_framework import viewsets
      from .models import Item
      from .serializers import ItemSerializer
      from django.shortcuts import render
      from django.http import JsonResponse
      
      class ItemViewSet(viewsets.ModelViewSet):
          queryset = Item.objects.all().order_by('name')
          serializer_class = ItemSerializer
          authentication_classes = [] 
          permission_classes = []
      
      def item_list(request):
          items = Item.objects.all()
          return render(request, 'main/index.html', {'items': items})
  • urls.py 패턴 추가

    • from django.urls import path, include
      from rest_framework.routers import DefaultRouter
      from . import views
      
      router = DefaultRouter()
      router.register(r'items', views.ItemViewSet)
      
      urlpatterns = [
          path('', views.item_list, name='item-list'),
          path('', include(router.urls)),
      ]

검색 추가

  • psycopg2설치

    • pip install psycopg2-binary
  • views.py에 검색로직 추가하는것으로 수정

    • import psycopg2
      
      from rest_framework import viewsets
      from .models import Item
      from .serializers import ItemSerializer
      from django.shortcuts import render
      from django.http import JsonResponse
      
      class ItemViewSet(viewsets.ModelViewSet):
          queryset = Item.objects.all().order_by('name')
          serializer_class = ItemSerializer
          authentication_classes = [] 
          permission_classes = []
      
      def item_list(request):
          items = Item.objects.all()
          return render(request, 'main/index.html', {'items': items})
      
      
      def search_item(request):
          name = request.GET.get('name', '')
          connection = psycopg2.connect(
              database="drf",
              user="postgres",
              password="8herLock698!",
              host="localhost",
              port="5432"
          )
          cursor = connection.cursor()
          cursor.execute("SELECT * FROM main_item WHERE name LIKE %s;", (f"%{name}%",))
          rows = cursor.fetchall()
          connection.close()
      
          result = [{"name": row[1], "description": row[2]} for row in rows]
          return JsonResponse(result, safe=False)
  • urls.py에 패턴 추가

    • from django.urls import path, include
      from rest_framework.routers import DefaultRouter
      from . import views
      
      router = DefaultRouter()
      router.register(r'items', views.ItemViewSet)
      
      urlpatterns = [
          path('', views.item_list, name='item-list'),
          path('search_item/', views.search_item, name='search_item'),
          path('', include(router.urls)),
      ]
  • index.html 수정+js로 fetch내용 추가

    • <!DOCTYPE html>
      <html lang="en">
        <head>
          <meta charset="UTF-8" />
          <title>DB검색</title>
        </head>
        <body>
          <h2>DB검색</h2>
          <input type="text" id="searchInput" placeholder="이름으로 검색" />
          <button id="searchButton">검색</button>
      
          <ul id="resultList"></ul>
      
          <script>
            function searchItems() {
              {% comment %} 이름으로 검색 {% endcomment %}
              let name = document.getElementById("searchInput").value;
              fetch(`/search_item/?name=${name}`)
                .then((response) => response.json())
                .then((data) => {
                  let resultList = document.getElementById("resultList");
                  resultList.innerHTML = "";
      
                  {% comment %} 반복문으로 가져온 데이터를 추가 {% endcomment %}
                  for (let item of data) {
                    let listItem = document.createElement("li");
                    listItem.textContent = `${item.name}: ${item.description}`;
                    resultList.appendChild(listItem);
                  }
                })
                .catch((error) => {
                  console.error("Error:", error);
                });
            }
      
            {% comment %} 클릭시 검색 실행 {% endcomment %}
            document
              .getElementById("searchButton")
              .addEventListener("click", function () {
                searchItems();
              });
      
            {% comment %} 엔터시 검색 실행 {% endcomment %}
            document
              .getElementById("searchInput")
              .addEventListener("keyup", function (e) {
                if (e.key === "Enter") {
                  searchItems();
                }
              });
          </script>
        </body>
      </html>
      
profile
비전공 오르미부트캠프 2기

0개의 댓글