【问题标题】:Search field in Django TemplateDjango 模板中的搜索字段
【发布时间】:2014-11-24 19:35:04
【问题描述】:

Django 模板中的搜索字段

如何在 Django 模板中创建类似于此图像的搜索字段

http://asciicasts.com/system/photos/1204/original/E354I01.png

我在 github 上试试这个 https://github.com/rg3915/vendas/commit/e0c67fd8154a3b8e450ec3db38705cdd7efc1350

但我不知道如何完成。

【问题讨论】:

  • 你现在看到了什么?你打电话给哪个网址/视图?你已经尝试过什么?

标签: django search django-templates field


【解决方案1】:

您说的是搜索字段,但本质上只是一个表单,您有一个输入(搜索框)并且您收到在您看来,该输入。

管理表单和 GET 操作的小示例:

views.py:

def your_view(request):
    ''' This could be your actual view or a new one '''
    # Your code
    if request.method == 'GET': # If the form is submitted

        search_query = request.GET.get('search_box', None)
        # Do whatever you need with the word the user looked for

    # Your code

模板

在你的模板中,最重要的是表单,你应该有这样的东西:

# Your template code
<form type="get" action="." style="margin: 0">
    <input  id="search_box" type="text" name="search_box"  placeholder="Search..." >
    <button id="search_submit" type="submit" >Submit</button>
</form>
# Your template code
  • action='.'
  • action='/other/url/'
  • 这个表单只是一个HTML表单,你也可以使用Django Forms

urls.py

您的 URL 文件必须与之前的相同。你不需要对你的实际 URL 做任何改变,它应该是这样的:

url(r'^your_url/?$', 'yourproject.views.your_view', name='your_url_name'),

无论如何,我建议您检查一些信息,例如:

【解决方案2】:

前端:模板

创建一个带有搜索框的表单(使用 html ,css)

<form type="get" action="exact_url" > 
    <input  id="search_box" type="text" name="search_box"  placeholder="Search..." > 
    <button id="search_submit" type="submit" >Submit</button> 
</form> 

后端查看

  • views.py

    中编写一个函数
  • 搜索 | Django 文档 | Django (https://docs.djangoproject.com/en/3.1/topics/db/search/#search) 使用它编写查询

  • jsonresponse 可以使用模板语言模板 | Django 文档 |姜戈 (https://docs.djangoproject.com/en/3.1/topics/templates/#the-django-template-language)

  • 使用 __contains 编写查询

       def your_view(request):
          if request.method == GET:  
              search_text = request.GET.get(search_box", None)
              records=Table.objects.filter(columnn__contains=search_text)     
              from django.http import JsonResponse
              return JsonResponse({"result_records":records})
    
  • 你的 url 应该和 **form(template) 中的一样 **and your_view 应该和 views.py 中的一样 (View)

       url(r'^exact_url/?$', 'yourproject.views.your_view')
    

【讨论】:

    猜你喜欢
    • 2018-03-23
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 2013-01-26
    • 2022-01-12
    • 2017-03-31
    相关资源
    最近更新 更多