html - 在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)
解决方案
您可以通过将数据保存到 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')
推荐阅读
- django - 模板无法访问 Django 收集的静态文件
- java - 是否有任何有效的微优化来找到唯一网格路径的数量?
- angular - 基于键值的角度更改ngClass
- java - 用户界面中的 JTable
- arrays - 当表确实存在并且具有值时,表 [1] 返回 nil
- c - 输入所需的骰子数后,我的 Yatzee 游戏代码将无法继续运行?
- java - 从多个孩子 Android Firebase 中检索同一个孩子
- python - 从多个子进程 Popens 一起捕获所有 stderr 数据
- java - List.of 和 List.copyOf 方法
- python - 进出 ModernGL 缓冲区的 Numpy 数组(使用 cv2 打开和保存)