[英]Django pass input data from an HTML file to a python script and then send the final data to another HTML file
我正在尝试在 Django 中构建一个简单的字典。 在 home.html 文件中有一个表单,它要求用户输入一个词。 这个词应该在需要它从 API 检索某些数据的 python 脚本中“成为一个变量”。
import json
import urllib.request
url = 'https://api.dictionaryapi.dev/api/v2/entries/en_US/' + user_input
response = urllib.request.urlopen(url)
result = json.loads(response.read())
final_word = str(result[0]['word']) + ' \n\n'
final_def = str(result[0]['meanings'][0]['definitions'][0]['definition']))
'user_input' 将是存储输入的变量
然后它应该将从 API 获得的数据(在本例中final_word
和final_def
传递给另一个 HTML 文件 final.html
我无法弄清楚如何做到这一点。 任何帮助表示赞赏。 如果我需要添加一些代码,请发表评论。 原谅我糟糕的英语。
因此,如果您尝试在视图中执行此操作。 假设你有两个模板
from django.shortcuts import render
import urllib.request
import json
def home(request): # your view name
if request.POST:
url = 'https://api.dictionaryapi.dev/api/v2/entries/en_US/' + request.POST['user_input']
response = urllib.request.urlopen(url)
result = json.loads(response.read())
context = {'word':result[0]['word'], 'meanings':result[0]['meanings']}
return render(request, 'output.html', context)
return render(request,'input.html')
这是一个快速使用的 html 模板
输入.html
<html>
<form action="#" method="post">
{% csrf_token %}
<input type="text" name="user_input">
<button>Go</button>
</form>
</html>
和测试输出
输出.html
<html>
<p>word: {{word}}</p>
<p>meaning: {{ meanings }}</p>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.