django在html之间传递变量

时间:2017-09-26 12:35:07

标签: python html django django-urls

您好我正在尝试创建一个搜索引擎,我需要让表ID保持在链接中。

在我的CrawledTables中有所有带有id的表...我需要通过链接将该id传递给var pk ...因为我请求获取该pk并使用获取表名的pk。然后使用表名来获取我搜索的表中的数据...并在这些表信息中创建一个搜索引擎。

错误:

Reverse for 'table_search' with no arguments not found. 1 pattern(s) tried: [u'search/(?P<pk>\\d+)/$']

这是我的 views.py

def search_form(request):
    return render(request, 'search/search.html')


def search(request):
    if 'q' in request.GET and request.GET['q']:
        q = request.GET['q']
        name = Crawledtables.objects.filter(name__icontains=q)
        return render(request, 'search/results.html', {'name': name, 'query': q})
    else:
        return HttpResponse('Please submit a search term.')


def search_form_table(request):
    return render(request, 'search/search_table.html', {'tbl_nm': table_name})


def search_table(request, pk):
    if 'q' in request.GET and request.GET['q']:
        q = request.GET['q']
        table_name = Crawledtables.objects.get(id=pk)
        print table_name
        t = create_model(table_name.name)
        print t
        title = t.objects.filter(title__icontains=q)
        print title
        return render(request, 'search/results_table.html', {'tbl_name': table_name,
                                                             'details': title,
                                                             'query': q})
    else:
        return HttpResponse("Please submit a search term!")

这是我的 search / urls.py

urlpatterns = [
    url(r'^results$', views.search, name='search'),
    url(r'^$', views.search_form, name='form'),
    url(r'^(?P<pk>\d+)/$', views.search_form_table, name='table_search'),
    url(r'^(?P<pk>\d+)/results$', views.search_table, name='table_results'),
]

这是我的 search.html

<form action="/search/results" method="GET">
    <input type="text" name="q">
    <input type="submit" value="Search">
</form>

results.html

<p> You searched for: <strong>{{ query }}</strong></p>
{% if name %}
    <p> Found {{ name|length }}</p>
    <ul>
        {% for nm in name %}
            <li><a href="{% url 'search:table_search' %}">{{ nm.name }}</a> {{ nm.date }}</li>

        {% endfor %}
    </ul>
{% else %}
    <p> No results found</p>
{% endif %}

search_table.html

<form action="/search/{{ pk }}/results" method="GET">
    <input type="text" name="q">
    <input type="submit" value="Search">
</form>

results_table.html

<p> You searched for: <strong>{{ query }}</strong></p>
{% if details %}
    <p> Found {{ details|length }}</p>
    <ul>
        {% for list in details %}
            <li> {{ list.title }}</li>
        {% endfor %}
    </ul>
{% else %}
    <p> No results found</p>
{% endif %}

1 个答案:

答案 0 :(得分:1)

由于<a href="{% url 'search:table_search' %}">中的results.html,您收到了错误消息。像这样更改href

{% for nm in name %}
    <li><a href="/search/{{ nm.id }}/">{{ nm.name }}</a> {{ nm.date }}</li>
{% endfor %}