2013-08-27 72 views
0

試圖在django中構建一個簡單的搜索頁面。試圖在Django中搜索記錄

我有一個模型:

class Person(models.Model): 
    ROLE_CHOICES = (
     ('Eng', 'Engineering'), 
     ('Product', 'Product'), 
     ('QA', 'QA'), 
     ('Mrkt', 'Marketing'), 
     ('Fin/Off', 'Finance/Office'), \ 
     ('Care', 'Care'), 
     ('Sales', 'Sales'), 
     ) 
    ROLE_TYPE = (
     ('Full', 'Full Time'), 
     ('CooP', 'Co-Op'), 
     ('Part', 'Part Time'), 
     ('Intern', 'Intern'), 
     ) 

    first_name = models.CharField(blank=True, max_length=100) 
    last_name = models.CharField(blank=True, max_length=100) 
    date_added = models.DateField(auto_now_add=True) 
    date_start = models.DateField(auto_now=False) 
    date_leaving = models.DateField(auto_now=False) 
    role = models.CharField(max_length=100, default = "", choices = ROLE_CHOICES) 
    manager = models.ForeignKey('self', limit_choices_to = {'is_manager': True}, null=True, blank=True) 
    title = models.CharField(blank=True, max_length=100) 
    role_type = models.CharField(max_length=100, default = "", choices = ROLE_TYPE) 
    laptop_needed = models.BooleanField(default=True) 
    phone_needed = models.BooleanField(default=True) 
    desk_loco = models.CharField(blank=True, max_length=100) 
    mail_lists = models.ManyToManyField(Mailists, blank=True, null=True) 
    notes = models.CharField(blank=True, max_length=500) 
    is_manager = models.BooleanField(default=False) 
    is_active = models.BooleanField(default=True) 
    is_leaving = models.BooleanField(default=False) 

    def __unicode__(self): 
     return u'%s %s' % (self.first_name, self.last_name) 

我有這樣的看法:

def search_people(request): 
    if request.method == 'POST': 
     search_text = request.POST['search'] 
    else: 
     search_text = '' 

    persons=Person.objects.filter(last_name__contains=search_text) 

    return render(request, 'hireterm/search.html', {'persons': persons}) 

從這種形式抓起:

  <form class="searchfield" method="get" action="/search/" autocomplete="off"> 
       Search: <input type="text" name="search"> 
       <input id="searchbuttonmain" type="submit" class="subbtn" value="Search"> 
      </form> 

,並呈現此頁:

{% if persons.count %} 

{% for p in persons %} 
    <p><a href="/edit_person/{{ p.id }}/">{{ p.last_name }}</a><p> 
{% endfor %} 

{% else %} 
    <p> OH NOES <p> 
{% endif %} 

它總是返回所有Perosns記錄,而不是按姓氏過濾的記錄,我不知道爲什麼。我相信我錯過了一些微不足道的東西,但我看不到它。感謝您的輸入。

回答

2

您的表單方法是GET,但它應該是POST。這導致它打到else-部分的if-陳述。因此Person對象在其last_name字段中包含空字符串被選中,但是它匹配所有對象。