[Python #17] [Django #10] 검색 기능에 UI 추가

in mini.topia4 years ago

pixabay

검색 기능에 UI를 추가한다. HTML의 form으로 우선 먼저 가볍게 구현해 보자. (깊게 구현할 능력도 안됨ㅎㅎ)

form 추가

먼저 django의 templates 폴더의 base.html 에 form 을 넣는다.

  1. action은 일단 하드코딩으로 /@june0620/search로 한다. 계정명은 변수로 처리하고 싶은데 안된다. ㅠ (#연구필요#장고초자)
  2. 검색 기능이니 method는 post보다는 get이 나을 것 같다.
  3. input 태그 세 개를 만들고 각각 tags, titles, texts 레이블 추가한다.
      <div>
          <p></p>
          <form action="/@june0620/search/" method="get">
              <label >Tags: </label>
              <input id="tags" type="text" name="tags" value="">
              <label >Titles: </label>
              <input id="titles" type="text" name="titles" value="">
              <label >Texts: </label>
              <input id="texts" type="text" name="texts" value="">
              <input type="submit" value="Search">
          </form>       
      </div>

대충 요런 화면인데 CSS가 없어서 이 모양이다. CSS 공부도 또 해야 하나? ㅠ 일단 기능에만 집중하자. 👇

URL 설정

form의 action으로 받은 url을 urls.py에 설정한다. 이 부분은 변수를 사용할 줄 아니 변수로 처리하자. ㅎㅎ
url 패턴과 매칭 될 경우 views.py의 SearchPosts 클래스를 호출한다.

    path('@<slug:account>/search/', SearchPosts.as_view(), name='search'),

form 파라미터 처리 및 검색

form 에서 전달받은 query string 을 리스트로 전환해야 하는데 split(',') 로 리스트화 및 query 딕셔너리에 추가한다.
UI 단에서 동일 필드에 여러 개 검색어를 입력하고자 할 때 , 로 분리하면 더 많은 결과를 얻을 것이다.
(일시적인 구현이고, 나중에 UI가 바뀌면 다시 구현 필요하다.)

class SearchPosts(ListView):
    template_name = 'album.html'
    context_object_name = 'all_posts'

    def get(self, request, *args, **kwargs):
        query = {
            'tags': request.GET.get('tags').split(','),
            'titles': request.GET.get('titles').split(','),
            'texts': request.GET.get('texts').split(',')
        }
        se = Search(account=kwargs['account'], query=query)
        self.queryset = se.search_posts()
        return super().get(request, *args, **kwargs)

결과

[Cookie 😅]
Python 3.7.4
Django 2.2.4
steem-python 1.0.1
goorm IDE 1.3

Sort:  

Congratulations @june0620! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s) :

You distributed more than 20000 upvotes. Your next target is to reach 21000 upvotes.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @hivebuzz:

HiveBuzz supports meetups of the Hive UK Community
Feedback from the September 1st Hive Power Up Day