Django - 基于搜索视图中的搜索查询渲染视图

时间:2016-11-16 16:49:11

标签: python django

我有一个非常基本的问题。我已阅读Django forms docs,但我仍然遗漏了一些内容。我希望在一个模板(testarray _________ 1 2 3 4 5 )中有一个搜索栏,并在另一个模板(search.html)中返回搜索查询。到目前为止,我有以下内容,使用this SO answer as a guide,它返回以下错误。谢谢你的帮助。

results.html

urls.py

Exception Value:    
results() missing 1 required positional argument: 'search_id'

forms.py

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^landing/', views.search, name='search'),
    url(r'^results/', views.results, name='results'),
]

views.py

from .models import Apartment
class Apt(forms.ModelForm):
  class Meta:
      model = Apartment
      fields = ('name')

landing.html上

def search(request):
    if request.method == 'POST': #the form has been submitted
        form = Apt(request.POST) #bound form
        if form.is_valid(): #validations have passed
            name = form.cleaned_data['name']
            u = Apt.objects.create(name=name)
            #REST query will go here.

            #commit to database
            u.save()

            return redirect('results', search_id=u.name)

    else: #create an unbound instance of the form
        form = Apt(initial={'name':'name'})
    #render the form according to the template, context = form
    return render(request, 'search/landing.html', {'form':form})

def results(request, search_id):
    search_id = request.POST.get('name')
    query = get_object_or_404(Apt, pk=search_id)
    return render(request, 'search/results.html', {'query':query} )

results.html

{% extends "base_simple.html" %}

{% block title %}Look up your name{% endblock %}

{% block main_content %}

<!-- Intro Header -->
<header class="intro">
    <div class="intro-body">
        <div class="container">
          <div class="inner cover">
            <h1 class="cover-heading">find your name</h1>
            <form id="searchform" method="POST" action="" accept-charset="utf-8">
            {% csrf_token %}
                <input id="apt" type="text" class="form-control" placeholder="Apartment Name" value="{{ Apt.name }}">
                <input type="submit" value="Search" class="btn btn-lg btn-default">
            </form>
          </div>            
        </div>
    </div>
</header>

{% endblock %}

1 个答案:

答案 0 :(得分:0)

在网址中,您需要将结果更改为

url(r'^results/(?P<search_id>.+)/', views.results, name='results'),

正则表达式中的命名组作为参数传递给视图

您还应该从结果视图中删除行search_id = request.POST.get('name'),因为重定向不包含任何POST数据