2016-04-04 74 views
0

我開始學習Django並定義了基於類的視圖,我創建了一個視圖,您可以手動輸入書籍的詳細信息,例如:title,author,...我還添加了搜索框在相同的觀點,應該自動查找api和網頁抓取的細節。應該在新視圖上顯示結果,根據用戶輸入而更改的新網址,以及用戶選擇最適合的多個結果。如何從html模板獲取關鍵字 - Django

問題是,我還不知道如何從定義的搜索框接收用戶輸入並將其傳遞給將操作它的另一個視圖(不同類)。

搜索模板框:

<div class="col-sm-offset-2 col-sm-10"> 
    <form id="custom-search-input" action="{% url 'find_book' %}" method="get" accept-charset="utf-8"> 
     <div class="input-group col-sm-10" > 
     <input type="text" class="form-control input-lg" placeholder="Find books" /> 
     <span class="input-group-btn"> 
      <button class="btn btn-info btn-lg" type="submit"> 
      <i class="glyphicon glyphicon-search"></i> 
      <i class="fa fa-search"></i> 
      </button> 
     </span> 
     </div> 
     </form> 
    </div> 

定義的類,其中用戶可以輸入:

class BookCreateView (CreateView, SuccessMessageMixin,): 
    model = Appointment 
    fields = ['title', 'author', 'time'] 
    success_message = 'Appointment successfully created.' 

    def get_context(self, **kwargs): 
     context = super(BookCreateView, self).get_context_data(**kwargs) 

類,我想要的結果顯示(不知道如何):

class BookFindView (View): 
    response_template = 'book_find.html' 

任何暗示或教程或文件建議將非常感激。

+0

這是一個關於如何Django Views可以接受用戶輸入的問題? (這個解決方案)(http://stackoverflow.com/a/21207496/1842146)應該做這個工作(我也認爲使用'def'而不是'class'來獲得這些簡單的視圖,就像BookFindView更可能是一個更好的選擇)。 –

回答

1

任何視圖都可以實現「get」和「post」處理;這樣你就可以有類似

class BookCreateView(views.View): 
    # subclass the basic form and add an hidden input named search 
    form = your_custom_search_form 
    # subclass the create model form 
    confirmation_form = your_custom_create_model_form 

def get(request): 
    # show the empty search page 
    # in your template use the form to implement search 

def post(request): 
    # handle the book search; there is a data in the payload named search 
    # you now have a payload to use; here you make a database query 
    # and return the similar books; every book is printed in the page 
    # using the your_custom_create_model_form that you can prepopulate 

    # handle the confirmation of the book otherwise; the post 
    # payload will contain the book information