【问题标题】:Passing value from one html template to another in Django在 Django 中将值从一个 html 模板传递到另一个模板
【发布时间】:2021-06-30 15:17:06
【问题描述】:

我正在使用 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)

【问题讨论】:

    标签: html django django-views django-forms django-templates


    【解决方案1】:

    您可以通过将数据保存到 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')
    

    【讨论】:

    • 谢谢,但是当我更改 from 操作方法时,我得到了错误提示“NoReverseMatch at / Reverse for 'result' not found.'result' 不是有效的视图函数或模式名称。”
    • 你的urls.py中的result叫什么?
    • 实际问题出在我的 result.html 文件上。我没有指定任何东西来接受来自主页的值。现在我可以传递价值了。感谢所有的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    • 2018-02-02
    • 2020-07-13
    相关资源
    最近更新 更多