2013-01-08 151 views
2

所以,我想創建一個超級基本窗體與一個單一的輸入字段,將用於查詢我的數據庫。Django窗體查詢數據庫(模型)

我的模型(models.py)如下:

from django.db import models 

class Book(models.Model): 
    uid = models.IntegerField(primary_key=True) 
    title = models.CharField(max_length=30) 
    class Meta: 
     db_table = u'books' 

forms.py

from django import forms 
from myapp.models import Book 

class EnterIDForm(forms.form): 
book_id = forms.CharField() 
# add a custom clean function to validate that the user input 
# is a valid book ID 
def clean_book_id(self): 
    try: 
     book_id = int(self.cleaned_data["book_id"]) 
    except: 
     book_id = None 

    if book_id and Book.objects.filter(uid=book_id).count(): 
     return book_id 
    else: 
     raise forms.ValidationError("Please enter a valid book ID number.") 

views.py

from django.shortcuts import render_to_response 
from myapp.models import Book 

def form_view(request): 
    if request.method == "POST": 
     # the user has submitted the form, see if we have a book 
     book_id_form = EnterIDForm(request.POST) # instantiate our form class with the user data 
     if book_id_form.is_valid(): 
      # if our form is valid, then we have a book_id that works: 
      the_book = Book.objects.get(uid=book_id_form.cleaned_data["book_id"]) 
       return render_to_response("book_template.html", { "the_book": the_book }, context_instance=RequestContext(request)) 
     # if the form wasn't valid, it will fall through to the other return statement. 
    else: 
     # If the user didn't submit a form, instantiate a blank one. 
     book_id_form = EnterIDForm() 
    return render_to_response("form_template.html", { "book_id_form": book_id_form }, context_instance=RequestContext(request)) 

我想輸入字段收集來自 「UID」用戶並顯示來自Book model instanc的所有數據e其中uid是數據庫中的某本書。

我理解表單是如何與視圖和後面的模板綁定的,但我似乎無法使其工作。

我已經無窮無盡地搜索了Django網站和許多其他資源,但我可以從中學習一些示例,但沒有任何結果。

任何人都在幫助我嗎?

謝謝。

+1

什麼是您的具體問題?你的表單代碼在哪裏? –

+0

正如Aamir所說,您嘗試使用的部分代碼可能會幫助我們發現問題所在。 – asermax

+2

安東尼,請編輯你的問題與表格代碼請,以及應該處理它的觀點。 –

回答

6

你可以在這裏做一個簡單的搜索。您不需要任何POST調用或表單創建。但是,如果你想創建一個表單,這應該仍然指向你正確的方向。

嘗試這樣:

search.html:

<form method="get" action="/search/"> 
    Search Notecards:<input type="text" name="q" id="id_q" value="{{ query }}"/> 
    <input type="submit" value="Search" /> 
</form> 

views.py:

from myapp.models import Book 
from django.template import RequestContext 
from django.shortcuts import render_to_response 

def search(request): 
    query = request.GET.get('q') 
    try: 
     query = int(query) 
    except ValueError: 
     query = None 
     results = None 
    if query: 
     results = Book.objects.get(uid=query) 
    context = RequestContext(request) 
    return render_to_response('results.html', {"results": results,}, context_instance=context) 

results.html:

{% if results %} 
    {% for result in results %} 
    {{ result.uid }} 
    {{ result.xxxx }} 
    {{ result.xxxx }} 
    {% endfor %} 
{% else %} 
    <h3 class='error'>Please enter a valid UID</h3> 
    <form method="get" action="/search/"> 
     Search Notecards:<input type="text" name="q" id="id_q" value="{{ query }}"/> 
     <input type="submit" value="Search" /> 
    </form> 
{% endif %} 
+0

您傳遞給搜索框的確切查詢是什麼?這是一個類型錯誤,所以它不會碰到except塊。 except塊除了值錯誤之外。您是否可以編輯原始帖子,以及如何在模板和搜索視圖中實施搜索框。 –

+1

您需要設置一個默認視圖 - 例如'home'。這可能非常簡單,並會加載search.html(搜索框)。在搜索框中輸入查詢後,您可以加載搜索視圖。這聽起來像你直接進入搜索視圖 - 導致「q」等於「無」。 我強烈建議通過Django教程。這很好。一旦你有了這個教程應用程序設置,你可以將上面的建議添加到應用程序,並看看它們的功能。然後,您可以重複使用您的應用所需的部分。 https://docs.djangoproject.com/zh/dev/intro/tutorial01/ –

+0

這段代碼對我不起作用,錯誤是'異常值:在賦值之前引用的局部變量'結果'。我的表單操作是發佈的,但我甚至無法到達,因爲您的方法沒有初始視圖。 –