首页 > 解决方案 > 在Django中将值从一个html模板传递到另一个模板

问题描述

我正在使用 Django 制作一个 Web 项目,并且对 Django 来说相对较新。
我被困在以下部分:
我想从一个 html 搜索框获取用户输入并将其显示在另一个 html 页面上。

这是我的第一页:

<html>
<head>
    <title>Title</title>
    <style type="text/css">
        #title{margin-top:150px;font-size:40px; font-family:"roboto"; text-align:center; color:grey}
        #info_text{margin-top:10px;font-size:15px; font-family:"roboto"; text-align:center; color:grey}
        #search_bar{height:40px;margin-top:20px;margin-bottom:9px;width:50%; margin-left: 24%}
        #search_button{height:50px;margin-top:20px;width:20%;margin-left: 40%;background-color:grey; font-size:40px; font-family:"roboto"; text-align:center; color: white}
    </style>
</head>
<body id="body">
    <div>
        <h1 id="title">Enter Value</h1>
        <form action="result" method="POST">
            {% csrf_token %}
            <input id="search_bar" type="text" name="search_box" onfocus="this.value=''">
            <input type="submit" value="Search" id="search_button">
        </form>
    </div>
</body>
</html>

这是我的 view.py 文件

from django.shortcuts import render
# Create your views here.

def home(request):
    return render(request, 'templates/home.html')

def result(request):
    raw_details = None
    if request.method == 'GET':
        raw_deatils = request.POST.get('search_box', None)
    print(raw_details)
    return render(request, 'templates/result.html', raw_details)

标签: htmldjangodjango-viewsdjango-formsdjango-templates

解决方案


您可以通过将数据保存到 django 来做到这一点sessions

 <form action="{% url 'result' %}" method="POST">
        {% csrf_token %}
        <input id="search_box" type="text" name="search_box" onfocus="this.value=''">
        <input type="submit" value="Search" id="search_button">
 </form>

意见:

def result(request):
    
    if 'search_box' in request.POST:
        request.session['search_data'] = request.POST['search_box']

    return render(request, 'templates/result.html')

现在输入的数据将保存在request.session['search_data']

您可以在其他视图中访问它,例如:

def exampleView(request):
    
    if 'search_data' in request.session:
        //...do something...//

    return render(request, 'exampleApp/exampleView.html')

推荐阅读