Top Banner
Blog 앱 앱앱 - 앱앱 앱앱 @sokunn
8

Django study part9

Jan 10, 2017

Download

Engineering

Seokgeun Kim
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Django study part9

Blog 앱 확장 - 검색 기능@sokunn

Page 2: Django study part9

개요» 다양한패키지들이있음» Django-haystack 패키지가많이사용됨

https://github.com/django-haystack/django-haystack» 간단한검색은장고자체의 Q- 객체를이용하여구현가능

2

Page 3: Django study part9

URLconf

blog/urls.pyurl (r'^search/$', SearchFormView.as_view(), name='search'),

» 뷰클래스 : SearchFormView 검색폼을보여주고폼데이터를처리 . FormView 를상속

» URL 패턴 : blog.search

3

Page 4: Django study part9

forms

blog/forms.pyfrom django import formsclass PostSearchForm(forms.Form): search_word = forms.CharField(label='Search Word')

» django.forms.Form 상속» CharField 는 TextInput 위젯 , label 은 input 앞의레이블로표시됨» search_word 는 input tag 의 id 및 name, label tag 의 id 에사용됨

4

Page 5: Django study part9

views

blog/views.py» 소스참조» SearchFormview: Formview → 제네릭뷰상속 Post 요청에대해

form_valid 함수실행후적절한 URL 로리다이렉트» 폼 , 템플릿지정» form_valid 함수오버라이딩 ( 안하면 Formview 의함수가실행됨 )» Q 객체로 filter 함수의매칭조건에 OR 적용가능

5

Page 6: Django study part9

templates

templates/base.html<li><a href="{% url 'blog:search' %}">Search</a></li>

» 상단메뉴에 "Search” 추가

6

Page 7: Django study part9

templates

templates/post_search.html» 소스참조» 검색폼출력 : csrf 토큰 , as_table 로 form 을테이블방식으로표시 ,

submit 버튼» 검색결과출력 : 검색결과가있을경우순회하며내용출력 , 검색

결과가없을경우 "<검색단어 > Not Found" 문장출력

7

Page 8: Django study part9

감사합니다8