0

尝试在 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 记录,而不是按姓氏过滤的记录,我不知道为什么。我确信我错过了一些微不足道的事情,但我看不到它。感谢您的输入。

4

1 回答 1

2

你的表单方法是GET,但它应该是POST。这会导致它命中else- 语句的 -if部分。因此选择Person在其字段中包含空字符串的对象last_name,但这匹配所有对象。

于 2013-08-27T16:20:30.973 回答