You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django问题:如何在搜索结果页面显示搜索关键词?

问题原因与解决办法

你的核心问题是没有将搜索关键词变量传入模板上下文(context)。模板里的{{ title_contains_query }}需要从views传递的context中取值,但当前代码的context里只包含了user_profile和user_profile_games_filter,没有title_contains_query,所以页面显示空白。

修复步骤

1. 在views.py中补充context变量

修改BootstrapFilterView函数,把搜索关键词变量加入上下文,同时可以优化代码结构避免重复:

def BootstrapFilterView(request):
    user_profile = User_Info.objects.all()
    user_profile_games_filter = Game_Info.objects.all()

    title_contains_query = request.GET.get('q')

    if is_valid_queryparam(title_contains_query):
        user_profile_games_filter = user_profile_games_filter.filter(game_title__icontains=title_contains_query)

    # 先初始化通用context,包含需要传递给模板的所有变量
    context = {
        'user_profile': user_profile,
        'user_profile_games_filter': user_profile_games_filter,
        'title_contains_query': title_contains_query  # 新增:传递搜索关键词
    }

    # 仅覆盖已登录用户的profile数据
    if request.user.is_authenticated:
        context['user_profile'] = User_Info.objects.filter(user=request.user)

    return render(request, "search_results.html", context)

2. 优化搜索框体验(可选)

如果希望提交搜索后,输入框保留用户的关键词,可以修改base.html里的input标签:

<input type="text" name="q" class="form-control gs-search-bar" placeholder="Search GameStation Games..." value="{{ title_contains_query|default:'' }}">

完成以上修改后,搜索结果页面就能正确显示用户输入的关键词了。

内容的提问来源于stack exchange,提问作者spidey677

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 11:20:07