【问题标题】:Search bar with Python-Django使用 Python-Django 的搜索栏
【发布时间】:2020-07-29 21:03:22
【问题描述】:

我正在尝试构建我的第一个 Django 博客,有人可以创建帐户、搜索和更新帖子,现在我想添加一个搜索栏,以便有人可以通过个人资料名称找到其他人。 但我不知道如何做到这一点,我试图在谷歌上找到一些东西,但没有任何帮助。

我试试这个:(在 base.html 上)

<form type="get" action="/other/path/" style="margin: 0">
    <input  id="search_box" type="text" name="search_box"  placeholder="Search..." >
    <button id="search_submit" type="submit" >Submit</button>

(在 views.py 上)

@login_required
def search_bar(request):
    if request.method == 'GET':
        search_query = request.GET.get('search_box', None)

(在 urls.py 上)

path('', UserPostListView.as_view() , name='search'),

【问题讨论】:

  • 您非常接近,但缺少什么?你有什么问题?问题越清楚,回答的机会就越大。
  • 非常感谢您的回答 pablo !我是新来的,如果我提出错误的问题很抱歉:) 我会尽力学习!

标签: django


【解决方案1】:
@login_required
def search_bar(request):
    if request.method == 'GET':
        search_query = request.GET.get('search_box', None)
        qs = YourModel.objects.filter(attribute__icontains = search_query)
        return render(request, 'search_results.html', {'results':qs})
        '''
        YourModel = Model where you want to run search
        attibute = attribute on your model where you want to run search
        search_results.html = is a seperate page where your search results will be displayed.
        '''

PS:这只是一个基本的例子。

【讨论】:

  • 非常感谢你! !
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多