django - django 模板中的按钮不会将数据放入数据库
问题描述
我有一个名为“mysite”的应用程序。我希望它执行一个python脚本,当单击按钮时,它将暂时将虚拟数据放入数据库(添加行)(最初我将从API中提取数据)但是单击按钮时没有任何反应。
网址.py
path('', views.index),
视图.py
from .fetch_data import get_data
def index(request):
if (request.method == 'POST' and 'script' in request.POST):
get_data()
return render(request, 'mysite/index.html')
“mysite/templates/mysite”文件夹中的 index.html
<form method="POST" name='script'>
{% csrf_token %}
<button type="submit" >Fetch data from source</button>
</form>
fetch_data.py
from .models import Hosts
import time, sys
def get_data():
print('here in function')
p = Hosts(hostname="first data")
p.save()
但是当我点击按钮时,什么也没有发生。即使成功单击按钮后,视图也应保持不变。
注意:fetch_data.py 与views.py 和urls.py 位于同一文件夹中。
解决方案
试试这个可能对你有帮助
from .fetch_data import get_data
def index(request):
if (request.method == 'POST'):
script = get_data.objects.all()
script.save()
return render(request, 'mysite/index.html')
推荐阅读
- ios - iOS Swift Core Data 如何从 NSFetchedResultsController 中搜索 FetchedObjects
- javascript - 将数据加载到输入字段:JQuery
- javascript - Chrome 中的脚本标签页
- javascript - 将 props 传递给 vue2 组件
- php - 在 Laravel 路由文件中包含这么多行路由可以吗?
- c# - Ajax 不调用 c# 函数但它是成功的。如何?
- html - 从 HTML 转换为 NSAttributedString 错误的属性
- math - 如何获得具有以下条件的数组的最大和?
- gradle - oracle驱动版本如何与版本推荐器确定
- pentaho - 从 PRPT 报告中导出图表数据